1

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?

user120242
  • 14,918
  • 3
  • 38
  • 52
Vinod
  • 925
  • 8
  • 9
  • You've found that you need to use JNI. The next step is to search for documentation or guides on *how* to use JNI. I just tried googling for "java jni documentation" and the first couple of links were to relevant documentation by Oracle (the company that now owns and maintains the official Java SE platform). – Peter May 17 '20 at 06:25
  • I think you're missing that the C++ code has to packaged in a DLL (or shared library), and the connection between the C++ code and the Java code is made at run time. You can't build C++ code and Java code together. – john May 17 '20 at 06:26

2 Answers2

1

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

Buddhika Bandara
  • 351
  • 1
  • 11
0

Your question is same as that of Call c function from Java you can reffer it

You need to use JNI

  • I once investigated a tool which converted compiled C++ code into Java byte code. It worked, so there are alternatives. But yes in practise you should use JNI. – john May 17 '20 at 06:29