To accomplish this I’m going to show using the JNI framework, which stands for Java Native Interface.
We will attempt to call the printf function of C++ just for the sake of demonstration.
First off we start by writing our Java code:
Pretty straightforward code, we declare a function called _cprint which of course has to be native then, in our entry point, we create a new instance of HelloUniverse to call _cprint which isn’t static.
Our static initializer will load the C++ DLL(from the classpath) making the call to _cprint possible.
After this, we create a DLL Win32 Project in Visual Studio.
Before jumping into C++ coding we have run the following commands to build the headers to integrate into our C++ project.
Tip: Create a small python or batch script to automate this if you are going to do a lot of compiling.
This will produce a header for C++ that has the methods that we’re declaring in Java.
Adding the generated header files into Visual Studio
Now we add the produced header to our “Header Files” in Visual Studio.
Also, if you see errors in this header that means you didn’t put the JNI path into “Include Directories” and “Library Directories”.
Now it’s time to write our native code!
This function will convert the jstring to const char* because that’s the only way we can use it in C++ after that don’t forget to free the variable with the JNI function to avoid memory leaks.
Keep in mind that free’ing the nativeString variable, not the Java one, and we need to do this because JNI allocated memory for it.
Note: if you use C++’s delete you would crash because that variable was allocated internally by the JVM, meaning that C++ wouldn’t know how to free it
Also, the architecture of the C++ DLL has to match the JVM.
Now we copy the DLL into the root folder of the Eclipse Project and run we get this output:
Tada! We successfully called a C++ function from Java!