Posted by kohsuke
on February 8, 2006 at 10:33 PM PST
I posted the first version of JNITL, a template library for developing C++ JNI application.
I posted the first version of JNITL , a template library for developing C++ JNI application.
As a C++ programmer, I always felt disappointed to see that JNI only supports C binding. Well, to be fair, it does a bare minimal C++ handling, like making JNI functions methods of the JNIEnv class, but any C++ programmer knows that we can do a lot better than that.
I've been writing a few native programs lately that interface with Java (like com4j , NLink , and kprofiler ), and the lack of good C++ support was really getting painful. Just to take one example, to invoke a Java method from JNI, you have to do:
- Obtain a class ID by giving a name (analogous to Class.forName)
- Obtain a method ID by giving a signature (analogous to Class.getMethod)
- Then use a JNI function to invoke this method.
Naturally, I wanted to do this easily. The obvious way to do this is to have a class that wraps the ID acqusition logic, so there goes two classes --- one for a class, another for a method. And then, when you invoke a method, you'd have to call a different JNI function depending on the return type of the method.
Since I can't care less about those details, I thought I should be able to just parameterize the method wrapper like this:
jint r = aMethodThatReturnsInt(object,arg1,arg2,...);
In doing this, I realized that this "call different function based on type" notion is very commonly seen in many places of JNI. So it makes sense to define another template so that mapping from type to those JNI methods can reused in other places.
In this way, in no time I found myself writing some 20 or so templates and their specializations to make those things work in a way it's supposed to be. I don't know how many of you out there still plays with C++, but for those of you who do, I hope you find this useful (or not, in which case I'd love to learn how it can be improved.)