Mapping between char* and byte[] in SWIG

In SWIG (A fairly good tool for Java program to access native libarary. http://www.swig.org), char* type in C++ will be automatically mapped to String type in Java, and vice versa. But how to map between char* in C++ to byte array in Java? The answer is simple as long as you just want to call C++ code from Java: include virous.i. in the interface file.

However, most of app using SWIG would not as simple as that, like, some might have callback between C++ and Java code. The aforementioned solution not work with callback since virous.i lacks the definition of callback mapping (Callbacks can be implemented by cross language polymorphism with directors from SWIG:  http://www.swig.org/Doc2.0/Java.html#Java_directors). Here I extended virous.i, which will got callback mapping works:

/*Director specific typemaps*/
%typemap(directorin, descriptor=”[B”) char *BYTE {
jbyteArray jb = (jenv)->NewByteArray(strlen(BYTE));
(jenv)->SetByteArrayRegion(jb, 0, strlen(BYTE), (jbyte*)BYTE);
$input = jb;
}
%typemap(directorout) char *BYTE {
$1 = 0;
if($input){
$result = (char *) jenv->GetByteArrayElements($input, 0);
if(!$1)
return $null;
}
}
%typemap(javadirectorin) char *BYTE “$jniinput”
%typemap(javadirectorout) char *BYTE “$javacall”

The idea is as simple as to implement director mappings among C++<->JNI<->Java.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment