Search code examples
javac++java-native-interface

How can I call C++ functions from Java?


I am working on a codebase at my current project where the front end has been coded using Java and the backend using C++. I am basically a C++ guy so not sure how I can invoke a C++ method from java code.

Can anyone point to a relevant link or provide some outline steps?

I tried googling but apart from the fact that I need to use JNI, I couldn't find much information.

I am getting used to the fact that unlike in C and C++ which includes header files, in Java you use the keywords package and import to get at code (functionality in terms of library?) elsewhere. So if I had the C++ code in a path say a/b/c in multiple header and source files (.h and .cpp), how can I use the above two constructs, i.e. package and import, to access the functionality provided by the code?


Solution

  • To call c++ functions from java,

    1. Create a header file (.h file) for a CPP program.
    2. Create CPP file
    3. Create a DLL
    4. In java code, declare the method as native, load the DLL using System.loadLibrary() method and call the method.

    Check this out for detailed instructions.

    Youtube Video : link

    And these links

    https://www.javaworld.com/article/2077513/java-tip-17--integrating-java-with-c--.html

    http://codemesh.com/products/vfour/tutorial/cpp/v3/L_12_going_native.html