SWIG/python array inside structure

前端 未结 3 1771
南方客
南方客 2020-12-01 22:01

I\'ve got a structure defined inside header.h that looks like :

typedef struct {
....
    int      icntl[40];
    double   cntl[15];
    int      *irn, *jcn;         


        
3条回答
  •  独厮守ぢ
    2020-12-01 22:39

    Have you considered using SWIG carrays?

    In your header file:

    typedef struct {
        int      icntl[40];
        double   cntl[15];
    } some_struct_t;
    

    Then, in your swig file:

    %module example
    %include "carrays.i"  
    // ...
    %array_class(int, intArray);
    %array_class(double, doubleArray);
    

    The Python looks like this:

    icntl = example.intArray(40)
    cntl = example.doubleArray(15)
    for i in range(0, 40):
        icntl[i] = i
    for i in range(0, 15):
        cntl[i] = i
    st = example.some_struct_t()
    st.icntl = icntl
    st.cntl = cntl
    

    You still can't set the structs directly. I write python wrapper code to hide the boilerplate.

    array_class only works with basic types (int, double), if you need something else (e.g. uint8_t) you need to use array_functions, which have even more boilerplate, but they work.

    http://www.swig.org/Doc3.0/SWIGDocumentation.html#Library_carrays

提交回复
热议问题