I have a pointer to a C structure and i need know how i can initialize the struct from python after generating the python library using swig.
I was able to compile the code and run swig without any errors , I was also able to import the library into python .
My aim is to learn how to use pointers with c/swig/python.
This is the c function i want to integrate into python :
#include <stdio.h>
#include "myswig.h"
myData* myhfun(myData *data){
data->s = data->r1 + data->r2;
printf("sum(%f+%f)=%f\n", data->r1, data->r2, data->s);
return data;
}
This is the header file for the same:
//file myswig.h
struct myData{
double r1;
double r2;
double s;
};
typedef struct myData myData;
myData* myhfun(myData *data);
My swig interface file looks like this
/* file: myswig.i */
%module myswig
%{
#include "myswig.h"
%}
/*my function */
myData* myhfun(myData *data);
Script to run swig and test:
swig -python -Isrc myswig.i
gcc -Isrc -fPIC -I/usr/include/python3.5m -I/usr/include/x86_64-linux-gnu/python3.5m -lpython3.5m -c src/myswig.c myswig_wrap.c
gcc -shared -fPIC -o _myswig.so myswig.o myswig_wrap.o
python3 -c "import myswig"
I found one way to achieve this ,
first write a function which initializes a struct pointer and returns the pointer to the struct,
you call this function from the python side and store the pointer value in a variable ,
now you can pass this variable around as if it were a pointer :).
C functions
Python code
Swig definition file