我试图弄清楚为什么在经过大量的困惑之后它会起作用
obo.librar_version 是一个 c 函数,需要 char ** 作为输入并执行 strcpy 传入字符。
from ctypes import *
_OBO_C_DLL = 'obo.dll'
STRING = c_char_p
OBO_VERSION = _stdcall_libraries[_OBO_C_DLL].OBO_VERSION
OBO_VERSION.restype = c_int
OBO_VERSION.argtypes = [POINTER(STRING)]
def library_version():
s = create_string_buffer('\000' * 32)
t = cast(s, c_char_p)
res = obo.library_version(byref(t))
if res != 0:
raise Error("OBO error %r" % res)
return t.value, s.raw, s.value
library_version()
上面的代码返回
('OBO Version 1.0.1', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '')
我不明白的是为什么 's' 没有任何值(value)?有人有主意吗?谢谢
最佳答案
当您将 s
转换为 c_char_p
时,您将在 t
中存储一个新对象,而不是引用。因此,当您通过引用将 t
传递给函数时,s
不会更新。
更新:
你确实是对的:
cast takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. It returns an instance of the second argument, which references the same memory block as the first argument.
为了获取对字符串缓冲区的引用,您需要使用以下内容进行转换:
t = cast(s, POINTER(c_char*33))
我不知道为什么 c_char_p
不创建引用,但你就知道了。
关于python - ctype问题字符**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1347280/