Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Java wrapper construction with JNI

I am currently writting a JNI wrapper for a C++ class and I'm not sure if what I have done so far is the most correct way.

As I understand it, it is not possible to declare a Java constructor native, so I ended up writing something like:

package log;

public class Logger
{
    private long internalPtr = 0;

    private native long createNativeInstance(String application, String module, String function);

    public Logger(String application, String module, String function)
    {
        this.internalPtr = createNativeInstance(application, module, function);
    }

    public native String getApplication();

    static { System.loadLibrary("log_java"); }
}

Basically, my internalPtr field holds the pointer to my underlying C++ instance and I create it in a pure Java constructor, using the static native method createNativeInstance().

Is this the correct way to do things ?

Another question which I could get an answer for is: "How should I handle the deallocation ?"

My Java skills are extremely limited, so do not hesitate to suggest even the more "obvious" solutions.

Thank you very much.

like image 958
ereOn Avatar asked Nov 04 '22 20:11

ereOn


1 Answers

That is the way I have always implemented native classes which wrap arround a C/C++ object. I think writing a native constructor could be a bit of a pain, so have never tried.

For de-allocation, you do a simolar thing. Write a C/C++ function which de-allocates the memory for your C/C++ object, and then call this from the java destructor (finalise method). So something like this:

private native void destroyNativeInstance( long p_internalPtr );

public void finalize()
{
    destroyNativeInstance( this.internalPtr );
}
like image 86
Sodved Avatar answered Nov 12 '22 10:11

Sodved