I\'m trying to use ctypes
. I\'m interested in manipulating C structs containing arrays. Consider the following my_library.c
#includ
There were 2 problems with the code (as I stated in the comment):
For more details, check [Python 3.Docs]: ctypes - A foreign function library for Python.
I modified your Python code, to correct the above mistakes (and some other minor stuff).
code00.py:
#!/usr/bin/env python3
import sys
import ctypes
DLL_NAME = "./my_so_object.so"
DOUBLE_10 = ctypes.c_double * 10
class ArrayStruct(ctypes.Structure):
_fields_ = [
("first_array", DOUBLE_10),
("second_array", DOUBLE_10),
]
def main():
dll_handle = ctypes.CDLL(DLL_NAME)
print_array_struct_func = dll_handle.print_array_struct
print_array_struct_func.argtypes = [ArrayStruct]
print_array_struct_func.restype = None
x1 = DOUBLE_10()
x2 = DOUBLE_10()
x1[:] = range(1, 11)
x2[:] = range(11, 21)
print([item for item in x1])
print([item for item in x2])
arg = ArrayStruct(x1, x2)
print_array_struct_func(arg)
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
Output:
[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q050447199]> python3 code00.py Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0] 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 7.000000 8.000000 9.000000 10.000000
Error #1. is a "duplicate" of (newer) [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer).