Python Ctypes:如何将Void*作为argumen传递

2024-10-01 09:20:03 发布

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

我必须在CTypes中使用DLL中的2个函数。这些函数有一个void*作为参数。但不管我怎么做,我都做不到。我得到一个错误告诉我我使用错误的类型。我看了很多帖子,看了医生,但我想不出来。 任何帮助都将不胜感激。我在windows上使用python2.7。在

我的C函数是:

void WriteRam(unsigned address, unsigned length, void* buffer)
void ReadRam(unsigned address, unsigned length, void* buffer)

在Python中,我尝试向函数传递一个列表,如下所示:

^{pr2}$

我的Python函数是:

WriteRam = DPxDll['DPxWriteRam']
def DPxWriteRam(address=None, length=None, buffer=None):
    #test = ctypes.c_void_p.from_buffer(buffer) # not working
    #p_buffer = ctypes.cast(buffer, ctypes.c_void_p) # not working
    p_buffer = ctypes.cast(ctypes.py_object(buffer), ctypes.c_void_p) # not working
    #p_buffer = ctypes.c_void_p() # not working
    WriteRam.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p] 
    WriteRam(address, length, ctypes.byref(p_buffer))

Tags: 函数noneaddressbuffer错误notctypeslength
1条回答
网友
1楼 · 发布于 2024-10-01 09:20:03

假设txBuff是一个整数列表,那么您需要将它们打包到一个数组中。下面的代码应该可以工作,但是我不能测试它。。。在

def DPxWriteRam(address, int_list):
    int_size = ctypes.sizeof(ctypes.c_int)
    item_count = len(int_list)
    total_size = int_size * item_count
    packed_data = (ctypes.c_int * item_count)(*int_list)
    WriteRam(ctypes.c_uint(address), ctypes.c_uint(total_size), packed_data)

DPxWriteRam(whatever, [0, 1, 2, 3])

…虽然WriteRam只是在做一个memcpy(),但是你可以使用这个。。。在

^{pr2}$

…我可以测试。。。在

>>> l = range(4)
>>> p = libc.malloc(1000)
>>> DPxWriteRam(p, l)
>>> s = ' ' * 16
>>> libc.memcpy(s, p, 16)
>>> print repr(s)
'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'

相关问题 更多 >