0

我正在尝试从 Python 访问 DLL 中的整数数组。我遵循 ctypes 文档页面中的指南,但我得到空指针访问异常。我的代码是:

if __name__ == "__main__":
    cur_dir = sys.path[0]
    os.chdir(cur_dir)
    api = CDLL("PCIE_API")
    PciAgentIndex=POINTER(c_uint32).in_dll(api, "PciAgentIndex")
    print(PciAgentIndex)
    print(PciAgentIndex[0])

我得到:

ValueError: NULL pointer access

当我打印最后一行时。

当我通过 Eclipse 调试器运行此代码片段并检查 PciAgentIndex 的内容属性时,我得到:

str: Traceback (most recent call last):
  File "C:\Program Files\eclipse\plugins\org.python.pydev_2.7.5.2013052819\pysrc\pydevd_resolver.py", line 182, in _getPyDictionary
    attr = getattr(var, n)
ValueError: NULL pointer access

我究竟做错了什么?我在 Windows 上并使用 Python 3.3.2。

4

1 回答 1

4

要澄清指针和数组之间的区别,请阅读 comp.lang.c 常见问题解答,问题 6.2:但我听说这char a[]char *a.

您正在从 DLL 中的数据创建一个指针。显然,数据以 4 个空字节(32 位 Python)或 8 个空字节(64 位 Python)开始。改用数组:

# for a length n array
PciAgentIndex = (c_uint32 * n).in_dll(api, "PciAgentIndex")

如果需要指针,还可以强制转换函数指针:

PciAgentIndex = cast(api.PciAgentIndex, POINTER(c_uint32))

一个 ctypes 数据对象有一个指向相关 C 数据缓冲区的指针。指针的缓冲区是 4 字节或 8 字节,具体取决于您的 Python 是 32 位还是 64 位。数组的缓冲区是元素大小乘以长度。in_dll是一个类方法,它使用 DLL 中的数据范围(不仅仅是副本)作为其缓冲区来创建实例。

于 2013-08-09T11:37:56.517 回答