我有一个公开函数的共享库:
const char* foo(const char* s);
要使用 ctypes 从 Python 调用它,我可以执行以下操作:
import ctypes
foo = ctypes.cdll.LoadLibrary('foo.so')
foo.foo.argtypes = [ctypes.c_char_p]
foo.foo.restype = ctypes.c_char_p
print(foo.foo('Hello World!'.encode('utf8')).decode('utf8'))
有没有办法将其嵌入到encode/decode('utf8')
类型本身中?我想执行以下操作:
foo.foo.argtypes = [c_utf8_p]
foo.foo.restype = c_utf8_p
print(foo.foo('Hello World!'))
我能够处理argtypes
以下问题:
class c_utf8_p:
@classmethod
def from_param(cls, obj: str):
return obj.encode('utf8')
但无法确定返回类型。restype
文档说将其赋值给任何非ctypes
类型都是不推荐的,而且会截断返回值,从而int
破坏 64 位指针。我尽量避免使用,errcheck
因为逻辑上我不会检查任何错误,而且它需要为每个函数设置两个属性。