6

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.

  • Unless you add a length to `Foo`, it sounds totally impossible since you can't magically deduce the length from the pointer alone. – unwind Aug 14 '12 at 12:36
  • @unwind I'm sorry, I've forgotten to add the `size` member. I've edit my question. – Svetoslav Marinov Aug 14 '12 at 12:39
  • Suppose you had more than 3 elements in your data structure. How would you access the 3rd element? Suppose you have an object `Foo x` with `x.size >= 3`. – pmg Aug 14 '12 at 12:45
  • I think to use/create a method like [foo_array_getitem](http://stackoverflow.com/a/8539253/906597) – Svetoslav Marinov Aug 14 '12 at 12:56

2 Answers2

3

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.

mibogo
  • 173
  • 1
  • 8
1

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.

C404
  • 243
  • 4
  • 14