Differences in ctypes between Python 2 and 3

Hernan picture Hernan · Aug 31, 2011 · Viewed 8.2k times · Source

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.

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

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

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

Thanks in advance

EDIT

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)

The python code is:

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)

This works in python 2.7 but not in 3.2.

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

In python, I am calling by:

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

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

Answer

multipleinterfaces picture multipleinterfaces · Aug 31, 2011

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.

Edit:

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