Python 2 和 3 之间 ctypes 的差异 [英] Differences in ctypes between Python 2 and 3

查看:28
本文介绍了Python 2 和 3 之间 ctypes 的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a working python 2.7 program that calls a DLL. I am trying to port the script to python 3.2. The DLL call seems to work (i.e. there is no error upon calling) but the returned data does not make sense.

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

Just in case it could be useful: - The call takes three arguments: two int (input) and a pointer to a ushort array (output).

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

I have tried using both python and numpy arrays without success.

谁能列举 Python 2.7 和 3.2 在 ctypes 方面的区别?

Can anyone enumerate the differences between Python 2.7 and 3.2 respecting ctypes?

提前致谢

编辑

这是一些示例代码.DLL 是专有的,所以我没有代码.但我确实有 C 头文件:

Here is some example code. The DLL is propietary so I do not have the code. But I do have the C header:

void example (int width, int height, unsigned short* pointer)

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)

这在 python 2.7 中有效,但在 3.2 中无效.

This works in python 2.7 but not in 3.2.

编辑 2

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

If the changes in ctypes are only those pointed out by Cedric, it does not make sense that python 3.2 will not work. So looking again at the code, I have found that there is a preparation function called before the function that I am mentioning. The signature is:

void prepare(char *table)

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

In python, I am calling by:

table = str(aNumber)
DLL.prepare(table)

问题是否可能是由于 Python 字符串处理的变化造成的?

Is it possible that the problem is due to the change in the Python string handling?

推荐答案

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

In Python 2.7, strings are byte-strings by default. In Python 3.x, they are unicode by default. Try explicitly making your string a byte string using .encode('ascii') before handing it to DLL.prepare.

#another way of saying table=str(aNumber).encode('ascii')
table = bytes(str(aNumber), 'ascii')
DLL.prepare(table)

这篇关于Python 2 和 3 之间 ctypes 的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆