从Python访问DLL中的数组

2024-10-02 22:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从Python访问DLL中的int数组。我遵循了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])

我得到:

^{pr2}$

当我打印最后一行时。在

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

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上使用python3.3.2。在


Tags: 代码in文档apidir页面数组ctypes
1条回答
网友
1楼 · 发布于 2024-10-02 22:31:12

要澄清指针和数组之间的区别,请阅读比较语言.c常见问题解答,问题6.2:But I heard that ^{} was identical to ^{}。在

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

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

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

^{pr2}$

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

相关问题 更多 >