Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C++ from Java?

I wanted to call a C++ method from Java. I read about JNI, but I am not getting how to get all the library files and where I should keep it in order to run the program from command line.

Is there any way to call a C++ method from Eclipse itself, because I am using it to run Java classes.

like image 995
user970500 Avatar asked Sep 29 '11 06:09

user970500


People also ask

Can you call C code from Java?

Java native interface (JNI) is a framework provided by java that enables java programs to call native code and vice-versa. Using JNI a java program has the capability to call the native C code.

How can I call C function in Java using native keyword?

Use javah -jni to generate a C header file ( HelloWorld. h ) containing the function prototype for the native method implementation. The javah tool is provided with JDK or Java 2 SDK releases. Write the C implementation ( HelloWorld.

Can I call C++ from Java?

How to call a C/C++ function from Java then you can use Java Native Interface (JNI), part of the Java platform, is an interface that enables communication between Java applications running on a Java Virtual Machine (JVM) and native applications or libraries written in other programming languages (e.g. C, C++).

Can you mix C and Java?

Calling a C/C++ function from Java is actually quite easy but requires several steps: The native method must be declared in your Java code. The Java Native Interface (JNI) glue layer needs to be implemented.


2 Answers

While I've used JNI-C++ bridging in the past (only a little though) - it can be a bit ugly. You might want to consider using SWIG to help you generate all the messy boiler plate code.

like image 172
Michael Anderson Avatar answered Oct 10 '22 00:10

Michael Anderson


If JNI is too complicated you can take a look at JNA. In first case you have to create native wrapper code (in C or C++) to join Java and native (C++/C/...) code. In second case it is done at runtime (so you only need Java code + config).

like image 39
Fernando Miguélez Avatar answered Oct 09 '22 23:10

Fernando Miguélez