python - ctypes python 中的浮点指针并传递结构指针

标签 python c++ c ctypes wrapper

我正在尝试将结构指针传递给 API 包装器,其中该结构包含浮点指针成员。我不确定我们如何将浮点指针值传递给结构。

/结构/

class input_struct (ctypes.Structure):
    _fields_ = [
        ('number1', ctypes.POINTER(ctypes.c_float)),
        ('number2', ctypes.c_float),
        #('option_enum', ctypes.POINTER(option))
    ]

/包装/

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()

最佳答案

您可以创建 c_float实例并使用指向该实例的指针进行初始化,或者创建一个 c_float数组并传递它,在 ctypes 中模仿指向其第一个元素的指针的衰减。

请注意ctypes.pointer()创建指向 ctypes现有实例对象同时 ctypes.POINTER()创建指针类型

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);
}

测试.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))

输出:

20.000000 100.000000
30.000000 100.000000

关于python - ctypes python 中的浮点指针并传递结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72826399/

相关文章:

python - 为什么 'functools.reduce' 和 'itertools.chain.from_itertools' 在嵌套列表合并时有不同的计算时间

java - 使用 Python-Selenium 启动 IE 时出错,而完全相同的脚本在 Java-Selenium 上运行良好

python - 监控 PI 上的两个 GPIO 引脚

c++ - 在 cout 语句中连接数组大小

正确输出后打印随机符号的C程序

c - 在C中的循环中读取回车键

c++ - sizeof(str -1) 和 sizeof(str) -1 之间的区别?

python - 将 NumPy 数组的指定元素转换为新值

c++ - 如何在线程退出时触发代码,而不使用函数 *_at_thread_exit?

C++仅使用指针更改数组的元素