Search code examples
javac++java-native-interfaceswigshared-ptr

Trouble passing boost::shared_ptr<> into NewObject()


Perhaps I'm being too ambitious here, but I'm trying to pass a shared_ptr back to Java through an Exception like so.

I am able to catch the Exception in java, but when I try to access any methods in the ManagementProcessor object itself I get a SIGSEGV. If I use new ManagementProcessorPtr() to send in an empty one I get the correct behavior (I throw a different exception).

Any insights?

Thanks!

-Chip

typedef boost::shared_ptr<ManagementProcessor> ManagementProcessorPtr;

%include "boost_shared_ptr.i"
%shared_ptr(ManagementProcessor);
%typemap(javabase) Exception "java.lang.RuntimeException";
%typemap(javabase) AuthenticationExceptionManagementProcessor "NS/Exception";

%exception {
try {
  $action
}
catch (AuthenticationException<ManagementProcessor> & e ) {
  jclass eclass = jenv->FindClass("NS/AuthenticationExceptionManagementProcessor");
  if ( eclass ) {
    jobject excep = 0;
    jmethodID jid;

    jstring message =  jenv->NewStringUTF(e.getMessage().c_str());
    jstring file =  jenv->NewStringUTF(e.getFileName().c_str());

    ManagementProcessorPtr* realm = new ManagementProcessorPtr(e.getRealm());
    jlong jrealm;
    *(ManagementProcessorPtr **)&jrealm = realm;

    jid = jenv->GetMethodID(eclass, "<init>",
        "("
        "LNS/ManagementProcessor;"
        "J"
        "Ljava/lang/String;"
        "Ljava/lang/String;"
        "J)V");
    if (jid) {
        excep = jenv->NewObject(eclass, jid,
            jrealm,
            e.getApiErrNum(),
            message,
            file,
            e.getLineNum());
        if (excep)  {
            jenv->Throw((__jthrowable*) excep);
        }
    }
  }

Client code:

} catch (AuthenticationExceptionManagementProcessor e) {
        java.lang.System.err.println(e);
        ManagementProcessor mp = e.getRealm();
        java.lang.System.err.println("got mp");
        java.lang.System.out.println(mp.getUUID());

}


Solution

  • And of course the right answer is that first I have to create the Java ManagementProcessor object with the ctor that takes a CPtr:

    jclass mpclass = jenv->FindClass("NS/ManagementProcessor");
    jobject jmp = 0;
    jmethodID mpid;
    ManagementProcessorPtr *realm = new ManagementProcessorPtr(e.getRealm());
    jlong jrealm;
    *(ManagementProcessorPtr **)&jrealm = realm;
    mpid = jenv->GetMethodID(mpclass, "<init>", "(JZ)V");
    jmp = jenv->NewObject(mpclass, mpid, jrealm, true);
    

    ...

            excep = jenv->NewObject(eclass, jid,
                jmp,
                e.getApiErrNum(),
                message,
                file,
                e.getLineNum());