[英]float pointer in ctypes python and pass structure pointer
I'm trying to pass a structure pointer to the API wrapper, Where the struct is containing float pointer member.我正在尝试将结构指针传递给 API 包装器,其中结构包含浮点指针成员。 I'm not sure that how we can pass float pointer value to the structure.
我不确定我们如何将浮点指针值传递给结构。
/ Structure / /结构/
class input_struct (ctypes.Structure):
_fields_ = [
('number1', ctypes.POINTER(ctypes.c_float)),
('number2', ctypes.c_float),
#('option_enum', ctypes.POINTER(option))
]
/ wrapper / /包装/
init_func = c_instance.expose_init
init_func.argtypes = [ctypes.POINTER(input_struct)]
#help(c_instance)
inp_str_ptr = input_struct()
#inp_str_ptr.number1 = cast(20, ctypes.POINTER(ctypes.c_float)) # want to pass pointer
inp_str_ptr.number1 = 20 # want to pass as float pointer
inp_str_ptr.number2 = 100
c_instance.expose_init(ctypes.byref(inp_str_ptr))
c_instance.expose_operation()
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.您可以创建一个
c_float
实例并使用指向该实例的指针进行初始化,或者创建一个c_float
数组并传递它,它在ctypes
中模仿指向其第一个元素的指针的衰减。
Note that ctypes.pointer()
creates pointers to existing instances of ctypes
objects while ctypes.POINTER()
creates pointer types .请注意,
ctypes.pointer()
创建指向现有ctypes
对象实例的指针,而ctypes.POINTER()
创建指针类型。
test.c - for testing test.c - 用于测试
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
typedef struct Input {
float* number1;
float number2;
} Input;
API void expose_init(Input* input) {
printf("%f %f\n",*input->number1, input->number2);
}
test.py测试.py
import ctypes
class input_struct (ctypes.Structure):
_fields_ = (('number1', ctypes.POINTER(ctypes.c_float)),
('number2', ctypes.c_float))
c_instance = ctypes.CDLL('./test')
init_func = c_instance.expose_init
# Good habit to fully define arguments and return type
init_func.argtypes = ctypes.POINTER(input_struct),
init_func.restype = None
inp_str_ptr = input_struct()
num = ctypes.c_float(20) # instance of c_float, similar to C "float num = 20;"
inp_str_ptr.number1 = ctypes.pointer(num) # similar to C "inp_str_ptr.number1 = #"
inp_str_ptr.number2 = 100
c_instance.expose_init(ctypes.byref(inp_str_ptr))
# similar to C "float arr[1] = {30}; inp_str_ptr = arr;"
inp_str_ptr.number1 = (ctypes.c_float * 1)(30)
c_instance.expose_init(ctypes.byref(inp_str_ptr))
Output:输出:
20.000000 100.000000
30.000000 100.000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.