Python 2和3之间的ctypes差异

Her*_*nan 14 python dll ctypes numpy python-3.x

我有一个调用DLL的python 2.7程序.我试图将脚本移植到python 3.2.DLL调用似乎工作(即调用时没有错误)但返回的数据没有意义.

以防它可能有用: - 调用有三个参数:两个int(输入)和一个指向ushort数组(输出)的指针.

我尝试过使用python和numpy数组都没有成功.

任何人都可以枚举Python 2.7和3.2之间的差异吗?

提前致谢

编辑

这是一些示例代码.DLL是propietary所以我没有代码.但我确实有C头:

void example (int width, int height, unsigned short* pointer)
Run Code Online (Sandbox Code Playgroud)

python代码是:

width, height = 40, 100
imagearray = np.zeros((width,height), dtype=np.dtype(np.ushort))
image = np.ascontiguousarray(imagearray)
ptrimage = image.ctypes.data_as(ct.POINTER(ct.c_ushort))
DLL.example(width, height, ptrimage)
Run Code Online (Sandbox Code Playgroud)

这适用于python 2.7但不适用于3.2.

编辑2

如果ctypes中的更改只是Cedric指出的那些,那么python 3.2不起作用是没有意义的.所以再看一下代码,我发现在我提到的函数之前有一个调用的准备函数.签名是:

void prepare(char *table)
Run Code Online (Sandbox Code Playgroud)

在python中,我通过以下方式调用:

table = str(aNumber)
DLL.prepare(table)
Run Code Online (Sandbox Code Playgroud)

该问题是否可能是由于Python字符串处理的变化引起的?

mul*_*ces 20

在Python 2.7中,字符串默认为字节字符串.在Python 3.x中,默认情况下它们是unicode..encode('ascii')在交付之前,尝试使用字符串显式地使用字符串DLL.prepare.

编辑:

#another way of saying table=str(aNumber).encode('ascii')
table = bytes(str(aNumber), 'ascii')
DLL.prepare(table)
Run Code Online (Sandbox Code Playgroud)

  • 几年过去了,这个答案非常实用!我也有一个问题,我在Python3中使用旧的python库,无法理解为什么代码不起作用.更改字符串后,我传递给共享库为ascii,一切正常! (2认同)