How to call Java functions from C++?


Question

How can I call Java functions from a C++ application?

I know about calling them from CMD (or similar techniques), but I would rather not use them.

1
46
9/17/2016 2:08:29 PM

Accepted Answer

As an example, check Creating a JVM from C. It shows a sample procedure to create a JVM and invoke a method. If the JVM already exists; e.g. your C program is invoked by the Java program (callback situation), you can cache the JNIEnv* pointer.

As an advice, be careful caching pointers to the JVM from C/C++, there are some semantics involved as to what you can cache and it could be invoked later on. For that, as Brian Agnew pointed out, check the JNI reference.

21
5/4/2009 10:40:51 AM

Check out the JNI Invocation interface. This will allow you to embed a JVM within your C (or C++) application.

Note that various easier mechanisms exist to facilitate calling C/C++ from Java (e.g. JNA). It may be worth considering inverting your problem such that you can call from Java (I understand this may well not be possible for your particular application, however)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon