tags:

views:

261

answers:

1

I have an existing library (JPhysX) that is a Java wrapper for a native C++ library (PhysX). The Java library makes use of types generated by SWIG, for example, com.jphysx.SWIGTYPE_p_NxStream, which represents a pointer to an NxStream object in the C++ code. Now I want to create my own C++ class that inherits from the C++ type NxStream, and have the Java wrapper for my class also inherit from the wrapper com.jphysx.SWIGTYPE_p_NxStream.

The problem is that when I call SWIG to generate the wrapper for my class, it also creates a new wrapper called SWIGTYPE_p_NxStream, which is functionally identical to the one in com.jphysx, but still a different type as far as Java is concerned.

How can I convince SWIG to reuse this existing wrapper from com.jphysx and make the wrapper of my class inherit from com.jphysx.SWIGTYPE_p_NxStream instead?

+1  A: 

Making the wrapper class explicitly inherit from the desired type did the trick in this case:

%typemap(javabase) UserStream "com.jphysx.SWIGTYPE_p_NxStream";

There were some methods in the wrapper class with which I had similar problems, but I simply removed them from the SWIG interface file because they aren't going to be called from the Java code anyway.

Edit: this does not work. Since the wrapper type inherits from another wrapper type, it suddenly has two swigCPtr fields. The one in the subtype is initialized, the one in the supertype remains 0... but this is the one that gets used when you use the supertype somewhere.

Edit 2: I finally solved the problem, by adding a method to the Java wrapper class to convert the UserStream object to a SWIGTYPE_p_NxStream object:

%typemap(javacode) UserStream %{
 public native com.JPhysX.SWIGTYPE_p_NxStream toNxStreamPtr();
%}

This JNI method was hand-written outside SWIG's stuff:

JNIEXPORT jobject JNICALL Java_physics_UserStream_toNxStreamPtr(JNIEnv *env, jobject userStreamObject) {
 jclass userStreamClass = env->GetObjectClass(userStreamObject);
 jmethodID getCPtrMethodID = env->GetStaticMethodID(userStreamClass, "getCPtr", "(Lphysics/UserStream;)J");

 jlong cPtr = env->CallStaticLongMethod(userStreamClass, getCPtrMethodID, userStreamObject);
 jboolean futureUse = false;

 jclass nxStreamPtrClass = env->FindClass("com/JPhysX/SWIGTYPE_p_NxStream");
 jmethodID nxStreamPtrConstructor = env->GetMethodID(nxStreamPtrClass, "<init>", "(JZ)V");
 jobject nxStreamPtrObject = env->NewObject(nxStreamPtrClass, nxStreamPtrConstructor, cPtr, futureUse);
 return nxStreamPtrObject;
}
Thomas