python - ctype问题字符**

标签 python ctypes

我试图弄清楚为什么在经过大量的困惑之后它会起作用

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/

相关文章:

python - pyqt5 覆盖 dropEvent python

python - Python 中的战舰

python gevent, zeromq, and ultramysql - 脑痛

windows - 如何使用 python 2.7 移动 Windows 桌面图标?

python - 在共享库中设置 NaN 陷阱

python - 从 python 中的共享库返回的数组 - 这是内存泄漏吗?

python - 向/从 Python 和 C 传递 2D 可变长度数组的好方法?

python - 尝试加入两个 pandas 数据帧但得到 "ValueError: You are trying to merge on object and int64 columns."?

sql-server - 如何在 SQL Server 中创建 Python CLR 过程?

python - 如何在 C 函数中访问 python 变量的数据? (参数类型 : void *)