I’m trying to pass a structure pointer to the API wrapper, Where the struct is containing float pointer member. I’m not sure that how we can pass float pointer value to the structure.
/Structure/
JavaScript
x
7
1
class input_struct (ctypes.Structure):
2
_fields_ = [
3
('number1', ctypes.POINTER(ctypes.c_float)),
4
('number2', ctypes.c_float),
5
#('option_enum', ctypes.POINTER(option))
6
]
7
/wrapper/
JavaScript
1
12
12
1
init_func = c_instance.expose_init
2
init_func.argtypes = [ctypes.POINTER(input_struct)]
3
4
#help(c_instance)
5
inp_str_ptr = input_struct()
6
#inp_str_ptr.number1 = cast(20, ctypes.POINTER(ctypes.c_float)) # want to pass pointer
7
inp_str_ptr.number1 = 20 # want to pass as float pointer
8
inp_str_ptr.number2 = 100
9
10
c_instance.expose_init(ctypes.byref(inp_str_ptr))
11
c_instance.expose_operation()
12
Advertisement
Answer
You can either create a c_float
instance and initialize with a pointer to that instance, or create a c_float
array and pass it, which in ctypes
imitates a decay to a pointer to its first element.
Note that ctypes.pointer()
creates pointers to existing instances of ctypes
objects while ctypes.POINTER()
creates pointer types.
test.c – for testing
JavaScript
1
15
15
1
#ifdef _WIN32
2
# define API __declspec(dllexport)
3
#else
4
# define API
5
#endif
6
7
typedef struct Input {
8
float* number1;
9
float number2;
10
} Input;
11
12
API void expose_init(Input* input) {
13
printf("%f %fn",*input->number1, input->number2);
14
}
15
test.py
JavaScript
1
23
23
1
import ctypes
2
3
class input_struct (ctypes.Structure):
4
_fields_ = (('number1', ctypes.POINTER(ctypes.c_float)),
5
('number2', ctypes.c_float))
6
7
c_instance = ctypes.CDLL('./test')
8
init_func = c_instance.expose_init
9
# Good habit to fully define arguments and return type
10
init_func.argtypes = ctypes.POINTER(input_struct),
11
init_func.restype = None
12
13
inp_str_ptr = input_struct()
14
num = ctypes.c_float(20) # instance of c_float, similar to C "float num = 20;"
15
inp_str_ptr.number1 = ctypes.pointer(num) # similar to C "inp_str_ptr.number1 = #"
16
inp_str_ptr.number2 = 100
17
18
c_instance.expose_init(ctypes.byref(inp_str_ptr))
19
20
# similar to C "float arr[1] = {30}; inp_str_ptr = arr;"
21
inp_str_ptr.number1 = (ctypes.c_float * 1)(30)
22
c_instance.expose_init(ctypes.byref(inp_str_ptr))
23
Output:
JavaScript
1
3
1
20.000000 100.000000
2
30.000000 100.000000
3