how to create object of a C++ class in my servlet ?

Christopher Schultz


This gets ugly, since you're not just calling discrete API functions from a Java wrapper (which is the case most of the time with JNI).

The short answer is: if you don't know how to do what you're trying to do, you probably shouldn't be doing it.

That being said...

What you'll have to do is create a series of native methods, each mirroring the methods in your C++ class. In addition, you'll need to have a 'createObjectOnHeap' method and a 'disposeObjectOnHeap' method.

In the constructor of your Java object, you'll have to call your 'createObjectOnHeap' function to actually instantiate your C++ object.

After you are done with your Java object, take care to call a 'dispose' method on it, which will call the 'disposeObjectOnHeap' function and destroy your C++ object.

Having never done this, I don't know where you'll keep the pointer to the C++ object between method calls... that's up to you.

Each member method in your Java class will either call or itself be a native method, which will simply make the appropriate call to your C++ object:

public native void doSomething();


void JNICall (etc...)

Doing all this is likely to get you very deep into trouble, and you may not be able to instantiate more than one of these things at a time, depending on the way you implement this.

My advise is to either re-write the C++ class in Java, or provide another way to manupulate these object (say, using a C++-based server process to which you can connect via a socket or HTTP-style request).

Good luck,

About | Sitemap | Contact