damtheman
damtheman

Reputation: 21

Wrapped C library in Python, but returned array is unchanged

This is my first attempt at using Ctypes. I have a C dll which does simple buffer manipulation of adding 1 to its contents.

extern "C"
{
    __declspec(dllexport) int AddBuffer(unsigned char* data, unsigned char len)
    {
        int i = 0;
        int sum = 0;
        for (i = 0; i < len; i++)
        {
            sum = sum + data[i];
            data[i] = data[i] + 1;
        }

        return sum;
    }
}

And in my python code I have

data = [1,2,3,4,5,8,4,6,9]
myfunc = test_dll.AddBuffer
myfunc.argtypes = (ctypes.POINTER(ctypes.c_uint8),ctypes.c_uint8)
data_array = ctypes.c_uint8 * len(data)
result = myfunc(data_array(*data),ctypes.c_uint8(len(data)))
print result
for i in range (0,len(data)):
     print  data[i]

The result I get is 42 but the contents of data remain unchanged. I have looked but still cannot find the reason.

Upvotes: 2

Views: 69

Answers (1)

This code:

data_array = ctypes.c_uint8 * len(data)
result = myfunc(data_array(*data),ctypes.c_uint8(len(data)))

Creates an anonymous copy of data, in an instance of a ctypes array type called data_array.

When you pass the data_array instance you anonymously create to your function that's what is getting modified, the new copy.

Instead you need:

data = [1,2,3,4,5,8,4,6,9]
myfunc = test_dll.AddBuffer
myfunc.argtypes = (ctypes.POINTER(ctypes.c_uint8),ctypes.c_uint8)
data_array = ctypes.c_uint8 * len(data)
arg = data_array(*data)
result = myfunc(arg,ctypes.sizeof(arg))
print result
for i in range (0,len(arg)):
     print  arg[i]

Which prints out the same array passed in to the function and makes sure the array you pass in is named instead of anonymous.

Upvotes: 1

Related Questions