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.

4
  • Unless you add a length to Foo, it sounds totally impossible since you can't magically deduce the length from the pointer alone. Commented Aug 14, 2012 at 12:36
  • @unwind I'm sorry, I've forgotten to add the size member. I've edit my question. Commented Aug 14, 2012 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. Commented Aug 14, 2012 at 12:45
  • I think to use/create a method like foo_array_getitem Commented Aug 14, 2012 at 12:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

I'm sorry. I didn't write the question right. Can you read it again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.