简体   繁体   English

传递空结构指针 ctypes

[英]passing null structure pointer ctypes

I am writing a Python wrapper for cpp APIs in that for one API I am trying to pass a NULL structure pointer as a parameter.我正在为 cpp API 编写一个 Python 包装器,对于一个 API,我试图将 NULL 结构指针作为参数传递。 Not sure how we can achieve that in Python.不确定我们如何在 Python 中实现这一点。

Below is my sample implementation:下面是我的示例实现:

cpp_header.hpp cpp_header.hpp

typedef enum {
    E_FLAG_ON = 0,
    E_FLAG_OFF
} option;

typedef struct {
    float *a;
    float b;
    char *file_path; 
    option flag;
} inputs;

// API
int op_init(const inputs*);

This is what happening inside the init API:这是 init API 内部发生的事情:

Implementation.cpp实现.cpp

int op_init(const inputs* usr_ptr) {
    internal_opration_read_set(&local_struct) { // local struct variable
         // read one input file and update the structure values
    }
    if (usr_prt !=  NULL) {
        internal_opration_update_set(usr_ptr, &local_struct) {
            // update the values only if i send NOT NULL structure
        }
    }
}

From cpp test application I'm passing NULL structure to initialize.从 cpp 测试应用程序我传递 NULL 结构来初始化。

test.cpp测试.cpp

int main() {
    inputs *usr_cfg = NULL;
    op_init(usr_cfg);
}

ctypes_imple.py ctypes_imple.py

From ctypes import *

class inputs(Structure):
    _fields_ = [('a', POINTER(c_float)),
                ('b', c_float),
                ('file_path', c_char_p),
                ('flag', option)]

# loading so file
so_lib = CDLL('some so')
# how we can initialize NULL structure pointer here?
so_lib.op_init() # how to send structure pointer as argument?

NOTE: this API reads inputs from a file and updates values to a structure in C. I am clueless how we can achieve the same in a Python wrapper?注意:此 API 从文件中读取输入并将值更新为 C 中的结构。我不知道如何在 Python 包装器中实现相同的功能? I mean updating values from so file runtime to a ctypes Python class.我的意思是将值从 so 文件运行时更新为 ctypes Python 类。

Use None to pass a null pointer:使用None传递一个空指针:

so_lib.op_init(None)

To send the actual structure instantiate one and send it.要发送实际结构实例化一个并发送它。 Best to define .argtypes and restype as well so ctypes doesn't have to guess and can perform better error checking:最好也定义.argtypesrestype ,这样ctypes就不必猜测并且可以执行更好的错误检查:

so_lib.op_init.argtypes = POINTER(inputs),
so_lib.op_init.restype = c_int

arg = inputs() # all initialized to zero/null by default.
so_lib.op_init(arg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM