Programming

Calling C++ Functions from Java

Today I will explain how to call Native Code(C/C++) in Java. To accomplish this we are going to use a framework called JNI, which stands for Java Native Interface.

We will attempt to call the function printf of C++ just for the sake of demonstration.

Java side

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”.

C++ side

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.

Testing

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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s