elams
elams

Reputation: 99

How to call a function in a c++ object file from java?

I have existing cpp files from a project which I would like to use it for my application which is in Java. I cannot change the cpp files. How can I call the functions from Java?

I'm working in Windows 10 using JavaFX for my application. I've seen some articles about JNI but none seem to solve my issue.

Upvotes: 2

Views: 277

Answers (2)

NoDataFound
NoDataFound

Reputation: 11949

If you package your library inside a shared object or a dll, you can also use JNA: https://github.com/java-native-access/jna or https://github.com/java-native-access/jna/blob/master/www/GettingStarted.md

For example, you already have mapping to Windows API. Another example is a mapping of mediainfo in Java: https://github.com/andersonkyle/mediainfo-java-api/blob/master/src/main/java/org/apothem/mediainfo/api/MediaInfo.java

Note that, as far as I understand it, this is based on JNI: it simplify the process since you mostly have to only declare interface on Java side and call appropriate method.

Upvotes: 2

darune
darune

Reputation: 10962

If JNI or swig is not desired or seems too low level,

A really blunt approach is to wrap the .cpp in c/c++ program and built an .exe that dumps to stdout/file. Then execute that in java via an external shell command.

Another good alternative is

Apache thrift

This basicly handles everything and goes everywhere so to speak (works by auto-generating code to target languages) and it is one I usually recommend in RPC situations. However there could be more setup cost involved (in the end, depends on your actual needs) - also since you need to host the .cpp in a service, in your case, locally.

Upvotes: 2

Related Questions