Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an array of pointers within a structure from Java with SWIG

Tags:

java

c

swig

I've something like this:

typedef struct {
    char * content;
} Boo;

typedef struct {
    Boo **data;
    int size;
} Foo;

I want to convert Boo ** data to an array with Boo elements (Boo[]) in Java with SWIG. And then to read the array (I don't want to edit,delete and create a new array from Java code). In the SWIG documentation is described how to do this with carrays.i and array_functions, but the struct's member data must be of type Boo*. Is there a solution of my problem?

EDIT: I've hurried and I've forgotten to write that I want to generate Java classes with SWIG to cooperate with C structures.

like image 972
Svetoslav Marinov Avatar asked Aug 14 '12 12:08

Svetoslav Marinov


2 Answers

The solution is very easy. Just use in a swig interface:

%include <carrays.i>
%array_functions(Boo *, boo_array);

And then access from java with:

SWIGTYPE_p_p_Boo results = foo.getData();
for(int i = 0; i < foo.getSize(); i++) {
    Boo booResult = foo.boo_array_getitem(results, i);
}

to retrieve the content of the array.

like image 173
Svetoslav Marinov Avatar answered Oct 30 '22 01:10

Svetoslav Marinov


you can always do a malloc, example for 1d tab would be :

int main (void)                                                          
 {                                                                
    int   size;                                                        
    Foo a;

  size = 2;
  if (!(a.data = malloc(size * sizeof(*(a.data)))))
   return (-1);
    // so you will have a.data[0] or a.data[1] ...

    //   for malloc on 2d                                   
    //   if (!(a.data[0] = malloc(size * sizeof(*(a.data)))))                
    //    return (-1);                                                     
  return 0;
 }

But since you start malloc you must use free after you done with the tab

Otherwise, change it to boo data[] or data[][] would require a precise number of struct stocked before you compile.

like image 21
C404 Avatar answered Oct 30 '22 01:10

C404