Python extension in C - passing lists back and forth

Viewed 96

I have a C library for a device that includes functions like:

int GetDevInfo(int *devices);

In this case, devices is an array of integers that might have been defined like this:

int devices[10]

The function will loop through a hardware bus to look for active devices. As it finds them, it puts the device number into the next available spot in devices[], so for example before scanning:

devices = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} and a global variable DeviceCount knows there are 0 active ones. The function does its magic and decides that devices 5 and 8 are active. So then:

devices = {5, 8, 0, 0, 0, 0, 0, 0, 0, 0} and DeviceCount knows there are 2.

I want the Python function to be something like this.

devices = list(range(64))
for i in range(0,len(devices)):  # Set them all to 0
    devices[i] = 0
DeviceCount = 0

# Now we'll update it
DeviceCount = myModule.GetDevInfo(DeviceCount, devices)

When it returns, DeviceCount might be set to 2, and devices looks like:

[5, 8, 0, 0, 0, 0, 0, 0, 0, 0]

I've written code for other wrappers that pass in integers and pass back strings, but I'm not finding any web wisdom to help me with this. I know if I do something like this:

def f(a, data):
    a.append(data)

l = [1, 2, 3]
f(l, 4)

I get l=[1, 2, 3, 4], but it's not obvious how to get that effect with a Python wrapper to C.

1 Answers
Related