如何使用 ctypes 将多行字符串从 Python 传递到 C?
How do I pass a multiline string from Python to C using ctypes?
我有以下简单的 C 函数:
void pyentry(const char *config)
{
printf("%s\n",config);
fflush(stdout);
}
我的ctypes定义如下:
libc = ct.CDLL("./amr.so")
entry = wrap_function(libc, 'pyentry', ct.POINTER(Checkpoint), [ct.c_wchar_p])
json = "this is a test"
start = entry(json)
其中 wrap_function
只是一个包装器,用于更轻松地定义 ctypes 对 C 函数的访问:
def wrap_function(lib, funcname, restype, argtypes):
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func
我已经编译为一个共享库,我正在尝试调用它,但在 C 中它只打印我发送的字符串的第一个字符。我假设这是因为我有错误的参数 tpyes in我的 ctypes 定义,但我没有找到正确的定义。
有人能告诉我为什么我的 C 函数只看到传递的字符串中的第一个字符吗?
尝试:
entry = wrap_function(libc, 'pyentry', None, [ct.POINTER(ct.c_char)])
json = "this is a test".encode('utf-8')
pyentry
取 const char*
和 returns void
。所以 argtypes
和 restype
可以是 [ct.POINTER(ct.c_char)]
和 None
.
而char*
指向一个字节序列,而不是Python字符串。所以 json
应该转换为字节。
我有以下简单的 C 函数:
void pyentry(const char *config)
{
printf("%s\n",config);
fflush(stdout);
}
我的ctypes定义如下:
libc = ct.CDLL("./amr.so")
entry = wrap_function(libc, 'pyentry', ct.POINTER(Checkpoint), [ct.c_wchar_p])
json = "this is a test"
start = entry(json)
其中 wrap_function
只是一个包装器,用于更轻松地定义 ctypes 对 C 函数的访问:
def wrap_function(lib, funcname, restype, argtypes):
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func
我已经编译为一个共享库,我正在尝试调用它,但在 C 中它只打印我发送的字符串的第一个字符。我假设这是因为我有错误的参数 tpyes in我的 ctypes 定义,但我没有找到正确的定义。
有人能告诉我为什么我的 C 函数只看到传递的字符串中的第一个字符吗?
尝试:
entry = wrap_function(libc, 'pyentry', None, [ct.POINTER(ct.c_char)])
json = "this is a test".encode('utf-8')
pyentry
取 const char*
和 returns void
。所以 argtypes
和 restype
可以是 [ct.POINTER(ct.c_char)]
和 None
.
而char*
指向一个字节序列,而不是Python字符串。所以 json
应该转换为字节。