SWIG & Java Use of carrays.i and array_functions for C Array of Strings

Posted by c12 on Stack Overflow See other posts from Stack Overflow or by c12
Published on 2012-03-19T23:27:56Z Indexed on 2012/03/19 23:29 UTC
Read the original article Hit count: 304

Filed under:

I have the below configuration where I'm trying to create a test C function that returns a pointer to an Array of Strings and then wrap that using SWIG's carrays.i and array_functions so that I can access the Array elements in Java.

Uncertainties:

  • %array_functions(char, SWIGArrayUtility); - not sure if char is correct
  • inline char *getCharArray() - not sure if C function signature is correct
  • String result = getCharArray(); - String return seems odd, but that's what is generated by SWIG

SWIG.i:

%module Test

%{
#include "test.h"
%}

%include <carrays.i>
%array_functions(char, SWIGArrayUtility);
%include "test.h"

%pragma(java) modulecode=%{
  public static char[] getCharArrayImpl() {
    final int num = numFoo();
    char ret[] = new char[num];
    String result = getCharArray();
    for (int i = 0; i < num; ++i) {
      ret[i] = SWIGArrayUtility_getitem(result, i);
    }
    return ret;
  } 

%}

Inline Header C Function:

#ifndef TEST_H
#define TEST_H

inline static unsigned short numFoo() {
  return 3;
}

inline char *getCharArray(){
    static char* foo[3];
    foo[0]="ABC";
    foo[1]="5CDE";
    foo[2]="EEE6";
    return foo;
}

#endif

Java Main Tester:

public class TestMain {
    public static void main(String[] args) {
        System.loadLibrary("TestJni");
        char[] test = Test.getCharArrayImpl();
        System.out.println("length=" + test.length);
        for(int i=0; i < test.length; i++){
            System.out.println(test[i]);
        }
    }

}

Java Main Tester Output:

length=3
?
?
,

SWIG Generated Java APIs:

public class Test {
  public static String new_SWIGArrayUtility(int nelements) {
    return TestJNI.new_SWIGArrayUtility(nelements);
  }

  public static void delete_SWIGArrayUtility(String ary) {
    TestJNI.delete_SWIGArrayUtility(ary);
  }

  public static char SWIGArrayUtility_getitem(String ary, int index) {
    return TestJNI.SWIGArrayUtility_getitem(ary, index);
  }

  public static void SWIGArrayUtility_setitem(String ary, int index, char value) {
    TestJNI.SWIGArrayUtility_setitem(ary, index, value);
  }

  public static int numFoo() {
    return TestJNI.numFoo();
  }

  public static String getCharArray() {
    return TestJNI.getCharArray();
  }


  public static char[] getCharArrayImpl() {
    final int num = numFoo();
    char ret[] = new char[num];
    String result = getCharArray();
    System.out.println("result=" + result);
    for (int i = 0; i < num; ++i) {
      ret[i] = SWIGArrayUtility_getitem(result, i);
      System.out.println("ret[" + i + "]=" + ret[i]);
    }
    return ret;
  } 


}

© Stack Overflow or respective owner

Related posts about swig