简体   繁体   中英

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. Not sure how we can achieve that in Python.

Below is my sample implementation:

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:

Implementation.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.

test.cpp

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

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? I mean updating values from so file runtime to a ctypes Python class.

Use None to pass a null pointer:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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