我在DLL中有函数并尝试在Python 3中调用它。函数原型是:
__declspec(dllexport) char* getmetadata(char* szFile, size_t* metadata_size);
Python代码是:
...
libm = ctypes.CDLL("libm.dll")
fc = libm.getmetadata
fc.restype = ctypes.c_char_p
fc.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_size_t)]
size = ctypes.c_size_t(0)
buffer = fc(bytes(path, "utf8"), ctypes.byref(size))
缓冲区的类型是字节。为什么不是c_char_p?
答案 0 :(得分:1)
ctypes
会自动将c_char_p
转换为Python的本机字节类型。这是一个方便:
from ctypes import *
dll = CDLL('msvcrt')
dll._getcwd.argtypes = c_char_p,c_int
dll._getcwd.restype = c_char_p
out = create_string_buffer(30)
print(dll._getcwd(out,30))
输出:
b'C:\\Users\\xxx\\Desktop'
但是使用c_char_p
以外的内容,你会得到一个ctypes
对象:
dll._getcwd.restype = POINTER(c_byte)
result = dll._getcwd(out,30)
print(result)
print(string_at(result))
输出:
<__main__.LP_c_byte object at 0x0000000002C81248>
b'C:\\Users\\xxx\\Desktop'