Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Native Access doesn't do C++, right?

I've found many references online (including some on stackoverflow) to JNA being used for C++ libraries, but nothing I can find in the JNA docs indicates that's possible. There doesn't seem to be any way to wrap a C++ class, in particular.

I need native access to use RTAudio, but all of RTAudio's functions are member functions of the RTAudio class. So just to confirm, JNA isn't the way to go right?

like image 859
Yuvi Masory Avatar asked Feb 11 '10 01:02

Yuvi Masory


4 Answers

What this question amounts to is asking how to call C++ instance methods using JNA, and it's possible, but you're going to have to do some work. In particular, you'll need to write a wrapper which extern "C"s any functions you actually need to invoke.

For any arbitrary type* function() definition you can map the method using JNA as returning a com.sun.jna.Pointer, but you won't be able to invoke methods on a C++ object from JNA.

A simple workaround for this would be to write a C interface library that simply invokes the method on the objects for you...so if you have some member function foo() you could export a C method from your C++ code:

extern "C" void bar(type* var){
   var->foo();
}

Obviously this will add some work for you...but I suspect the overhead for switching to JNI would be about the same.

JNA only cares about the way in which the method is exported in the DLL -- and that must be without C++ decorations (hence the extern "C"), so you can do whatever you need to within any such method without exposing methods that you call.

In my contrived example above, this means that foo(), as long as it is defined within the DLL does not in fact have to even be exposed. Since it's a C++ function, JNA cannot call it directly, but it can be called from within a function that JNA can call, which is why my proposed solution works.

So, yes, you can fully encapsulate calls to all the member functions (create, operate, destroy) in a single function and JNA won't care.

like image 108
Mark Elliot Avatar answered Nov 20 '22 01:11

Mark Elliot


Try Swig. It will create wrappers for c++ classes for you.

like image 26
Denis Tulskiy Avatar answered Nov 20 '22 01:11

Denis Tulskiy


BridJ is a spiritual child of JNA that adds some limited C++ support (+ full support from JNAerator). If you're not using too many templates it might just work...

(disclaimer: I'm the author of BridJ & JNAerator)

like image 26
zOlive Avatar answered Nov 20 '22 00:11

zOlive


Youre right JNA is for accesing native libraries. I think what you need is a Java - COM Bridge. If this is the case there are a few free alternatives:

JCOM http://sourceforge.net/projects/jcom

Jacob http://sourceforge.net/projects/jacob-project

I've used Jacob in the pass with good results, but I think it's a little bit outdated.

like image 1
Alonso Avatar answered Nov 20 '22 01:11

Alonso