Interfacing C struct with int * member in Python

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Interfacing C struct with int * member in Python

Robin Verschueren
Dear SWIG users,

I'm struggling since two days to interface the following C struct with Python using SWIG. Ideally, I want to use it from Python as follows:

ms = my_struct()
ms.some_int = 5
ms.some_int_vector = [1,2,3,4,5] # or NumPy array equivalent

Look below for what I have so far (I first try to allocate just one int for some_int_vector for debugging purposes). In Python, some_int does what it's supposed to, however, for some_int_vector I get 'None'. 

Any help is appreciated, as it seems something so basic, but yet I do not see what I do wrong. Also, probably this can be all done with SWIG built-ins, and I don't need custom %typemaps?

Best regards,
Robin

// File test.h
typedef struct {
    int some_int;
    int *some_int_vector;
} my_struct;

// File test.i
%module test
%{
#define SWIG_FILE_WITH_INIT
#include "swig/test.h"
%}

%include "typemaps.i"
%include "numpy.i"
%init %{
import_array();
%}

%typemap (in) int * {
    $1 = (int *) malloc(sizeof(int));
    printf("Allocated 1 int\n");
    $1[0] = 55;
}

%typemap (out) int * {
    $result = PyInt_FromLong(*$1);
}

%typemap (memberin) int * {
    memmove($1, $input, sizeof(int));
}

%include "swig/test.h"



------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, SlashDot.org! http://sdm.link/slashdot
_______________________________________________
Swig-user mailing list
[hidden email]
https://lists.sourceforge.net/lists/listinfo/swig-user
Loading...