How to generate Java array from C pointer in SWIG -


given c code:

typedef struct _b {  /* */ } b;  typedef struct _a {     int numbs; /* count of bs in array bellow */     b *b; } a; 

i access a.b array in java

a = new a(); b[] b = a.getb(); 

do have idea how swig? played around carrays.i, without success. consider b *b not have array, in particular structure.

we can swig. tricky part spotted swig inclined assume b* pointer object, not start of array.

since array contains many non-primitive instances each instance going require creation of java object proxy corresponding b instance in c array. there 2 places cause generated. either write c creates each object , sticks in jobjectarray, or write java takes advantage of fact swig can trivially made generate specific proxy specific member. think latter solution simpler , cleaner i've made example using approach:

%module test  %ignore a_::b; // wrap way %typemap(javacode) %{   public b[] getb() {     b[] ret = new b[getnumbs()];     (int = 0; < ret.length; ++i) {       ret[i] = getb(i);     }     return ret;   } %}  // or %include etc. %inline %{ typedef struct b_ {  /* */ } b;  typedef struct a_ {     int numbs; /* count of bs in array bellow */     b *b; } a; %}  %javamethodmodifiers a_::getb(size_t pos) "private"; %extend a_ {   // defaults non-owning, want   b *getb(size_t pos) {     assert(pos < $self->numbs); // todo: real error handling     return $self->b+pos;   } } 

the %extend provides 1 method in java gets b in c array of bs. since implementation detail made private.

we told swig not wrap b *b pointer - we're going supply our own wrapping manually instead. provided via javacode typemap. inside typemap build our java array calling our helper once per item in array.

with in place it's sufficient do:

a = new a(); b[] b = a.getb(); 

crucially because ignored specific member of a won't interfere other uses of b *b.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -