2024-10-01 04:45:10 发布
网友
有人能给我演示一个非常简单的pythonctypes示例,其中包含Unicode字符串包括C代码?
比方说,一种获取pythonunicode字符串并将其传递给一个C函数的方法,该函数将其与自身连锁并将其返回给Python,后者将其打印出来。在
未经测试,但我认为这应该行得通。在
s = "inputstring" mydll.my_c_fcn.restype = c_char_p result = mydll.my_c_fcn(s) print result
至于内存管理,我的理解是c代码需要管理它创建的内存。也就是说,它不应该释放输入字符串,但最终需要释放返回字符串。在
from ctypes import * buffer = create_string_buffer(128) cdll.msvcrt.strcat(buffer, "blah") print buffer.value
Note: I understand that the Python code is easy, but what I'm struggling with is the C code. Does it need to free its input string? Will its output string get freed by Python on its behalf?
不,您需要自己手动释放缓冲区。人们通常所做的是立即从缓冲值,然后释放缓冲区。在
Can you post the C code? – mike 2 hours ago
这个程序使用ctypes从Python调用^{}。它将a和b连接到缓冲区中,缓冲区的长度不足以让a + b + (null terminator)演示更安全的n版本。在
ctypes
a
b
a + b + (null terminator)
n
必须传递create_unicode_buffer(),而不是为非常数wchar_t*传递常规的不可变u"unicode string",否则可能会出现分段错误。在
create_unicode_buffer()
wchar_t*
u"unicode string"
如果需要与之对话的函数返回UCS-2和sizeof(wchar_t) == 4,那么您将无法使用unicode_buffer(),因为它在{}之间转换为Python的内部Unicode表示。在这种情况下,您可以使用result.create_string_buffer()和result.decode('UCS2')的组合,或者只创建一个c_short和{}的数组。为了调试ODBC驱动程序,我不得不这么做。在
sizeof(wchar_t) == 4
unicode_buffer()
result.create_string_buffer()
result.decode('UCS2')
c_short
在示例.py公司名称:
#!/usr/bin/env python #-*- encoding: utf-8 -*- import sys from ctypes import * example = cdll.LoadLibrary(".libs/libexample.so") example.its_an_example.restype = c_wchar_p example.its_an_example.argtypes = (c_wchar_p, c_wchar_p, c_uint) buf = create_unicode_buffer(19) # writable, unlike u"example". buf[0] = u"\u0000" a = u"あがぃいぅ ☃ " b = u"個人 相命理 網上聯盟" print example.its_an_example(buf, a, len(buf) - len(buf.value) - 1) print example.its_an_example(buf, b, len(buf) - len(buf.value) - 1) print buf.value # you may have to .encode("utf-8") before printing sys.stdout.write(buf.value.encode("utf-8") + "\n")
示例c:
Makefile:(确保缩进是一个制表符,而不是空格):
all: libtool mode=compile gcc -g -O -c example.c libtool mode=link gcc -g -O -o libexample.la example.lo \ -rpath /usr/local/lib
未经测试,但我认为这应该行得通。在
至于内存管理,我的理解是c代码需要管理它创建的内存。也就是说,它不应该释放输入字符串,但最终需要释放返回字符串。在
不,您需要自己手动释放缓冲区。人们通常所做的是立即从缓冲值,然后释放缓冲区。在
^{pr2}$这个程序使用} 。它将
ctypes
从Python调用^{a
和b
连接到缓冲区中,缓冲区的长度不足以让a + b + (null terminator)
演示更安全的n
版本。在必须传递
create_unicode_buffer()
,而不是为非常数wchar_t*
传递常规的不可变u"unicode string"
,否则可能会出现分段错误。在如果需要与之对话的函数返回UCS-2和}之间转换为Python的内部Unicode表示。在这种情况下,您可以使用}的数组。为了调试ODBC驱动程序,我不得不这么做。在
sizeof(wchar_t) == 4
,那么您将无法使用unicode_buffer()
,因为它在{result.create_string_buffer()
和result.decode('UCS2')
的组合,或者只创建一个c_short
和{在示例.py公司名称:
示例c:
^{pr2}$Makefile:(确保缩进是一个制表符,而不是空格):
相关问题 更多 >
编程相关推荐