Maximilian
Maximilian

Reputation: 1375

Access struct in Python using SWIG

Do I have to completely redefine a given struct (given in a .c file, which is included in the compilation) in the interface file to make it accessible via python?

EDIT: If it is defined in a header file, I only have to include the header file in the interface file, right?

Upvotes: 1

Views: 547

Answers (1)

luoluo
luoluo

Reputation: 5533

I think you don't have to, except you want to add member functions to C structures.

/* file : vector.h */
...
typedef struct {
    double x,y,z;
} Vector;


// file : vector.i
%module mymodule
%{
    #include "vector.h"
%}

%include "vector.h"          // Just grab original C header file

Adding member functions to C structures

/* file : vector.h */
...
typedef struct {
    double x,y,z;
} Vector;


// file : vector.i
%module mymodule
%{
    #include "vector.h"
%}
%extend Vector {             // Attach these functions to struct Vector
    Vector(double x, double y, double z) {
        Vector *v;
        v = (Vector *) malloc(sizeof(Vector));
        v->x = x;
        v->y = y;
        v->z = z;
        return v;
    }
    ~Vector() {
        free($self);
    }
    double magnitude() {
        return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z);
    }
    void print() {
        printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z);
    }
};

SWIG-1.3 Documentation

Upvotes: 2

Related Questions