I have a C++ program to receive binary data from network. After data is received, it will callback the data as a byte array from C++ to a Java client. I use the director feature in SWIG to easily achieve cross language polymorphism across C++ and Java for callback. Here's a link .
But I found there is no typemaps in SWIG from char* in C++ to byte[] in Java. So, I added a patch to the virous.i. Here's a link .
/*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;
jenv->ReleaseByteArrayElements($input, $result, 0);
}
}
%typemap(javadirectorin) char *BYTE "$jniinput"
%typemap(javadirectorout) char *BYTE "$javacall"
For example. I have a class in C++ called A:
class A{
public:
virtual void onDataReceived(const char* BYTE, const size_t len) {}
};
Then in Java code I have another class B to extend A:
class B extends A {
@Override
public void onDataReceived(byte[] data, long len) {
//handling the data.
}
}
I can receive the byte array in Java code, but it seems it is never garbage collected by JVM. The onDataReceived method in SWIG generated wrapper file is like this:
void SwigDirector_A::onDataReceived(char const *BYTE, size_t const len) {
JNIEnvWrapper swigjnienv(this);
JNIEnv * jenv = swigjnienv.getJNIEnv();
jobject swigjobj = (jobject) NULL;
jbyteArray jBYTE = 0;
jlong jlen;
if (!swig_override[3]) {
A::onDataReceived(BYTE,len);
return;
}
swigjobj = swig_get_self(jenv);
if (swigjobj && jenv->IsSameObject(swigjobj, NULL) == JNI_FALSE) {
{
jbyteArray jb = (jenv)->NewByteArray(strlen(BYTE));
(jenv)->SetByteArrayRegion(jb, 0, strlen(BYTE), (jbyte*)BYTE);
jBYTE = jb;
}
jlen = (jlong) len;
jenv->CallStaticVoidMethod(Swig::jclass_DataTransferJNI, Swig::director_methids[3], swigjobj, jBYTE, jlen);
if (jenv->ExceptionCheck() == JNI_TRUE) return;
} else {
SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null upcall object");
}
if (swigjobj) jenv->DeleteLocalRef(swigjobj);
}
In my C++ code, I will delete the data in the receive buffer after the callback is done. But I checked from Java VisualVM that the memory used by java client process is not GC-ed after a long time. Thanks advance for any help!
PS. The data is quite large, it is around 32KB.
I got it solved by added deletion of reference to jb in Director typemaps: (jenv)->DeleteLocalRef(jb);
Here's the updated patch .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.