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
#include<stdlib.h>
#include "myswig.h"
myDataHolder* initStructMem(){
myDataHolder *myStruct;
myStruct=malloc(sizeof(myStruct));
return myStruct;
}
myDataHolder* setVal(int a ,int b, myDataHolder *data){
data->r1=a;
data->r2=b;
return data;
}
int getSum(myDataHolder *data){
data->s = data->r1 + data->r2;
return 0;
}
void printVal(myDataHolder *data){
printf("sum of %d and %d = %d",data->r1, data->r2, data->s);
}
Python code
import myswig
x = myswig.initStructMem()
y = myswig.setVal(1,2,x)
myswig.getSum(y)
myswig.printVal(y)
Swig definition file
/* file: myswig.i */
%module myswig
%{
#include "myswig.h"
%}
/*my func */
myDataHolder* initStructMem(void);
myDataHolder* setVal(int a ,int b, myDataHolder *data);
int getSum(myDataHolder *data);
void printVal(myDataHolder *data);
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.