1

我必须在 CTypes 中使用 DLL 中的 2 个函数。这些函数有一个void*as 参数。但无论我尝试什么,我都无法让它发挥作用。我收到一条错误消息,告诉我我使用了错误的类型。我看过很多帖子并阅读了文档,但我无法弄清楚。任何帮助,将不胜感激。我在 Windows 上使用 Python 2.7。

我的 C 函数是:

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

在 Python 中,我试图将列表传递给函数,如下所示:

audioVolume = 32767
for i in range(buffSize):
    txBuff.append(int(audioVolume * math.sin(i)) )
WriteRam(0, 64, txBuff)

我的 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))
4

1 回答 1

2

Assuming txBuff is a list of integers, then you'll need to pack them into an array. The following code ought to work, but I can't test it...

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])

...although if WriteRam is pretty much just doing a memcpy(), then you could just use this...

import ctypes
libc = ctypes.CDLL('msvcrt.dll')

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)
    libc.memcpy(address, packed_data, total_size)

...which I can test...

>>> 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'
于 2013-05-21T19:04:08.917 回答