pythonpython-3.xctypescross-language

How to cast a python list into a pointer of type void in C


I'm trying to learn how to use ctypes in Python and I came across this example in the documentation

class Bar(Structure):
   _fields_ = [("count", c_int), ("values", POINTER(c_void_p))]

bar = Bar()
bar.values = (c_void_p * 3)(1, 2, 3)
bar.count = 3
for i in range(bar.count):
    print(bar.values[i])

This would print

1
2
3

What I actually want is to convert an actual python list such as arr = [1,2,3] into the compatible type of bar.values in the example above. Is there any way that I could achieve such thing?


Solution

  • If I understand you correctly, all you want is to have an assignment for values based on an variable instead of hard coded numbers.

    Then this will work

    arr = [1, 2, 3, 4]
    bar = Bar()
    bar.values = (c_void_p * len(arr))(*arr)
    bar.count = len(arr)