How to call c++ functionality from java

江枫思渺然 提交于 2019-12-12 08:08:24

问题


I have a Java program that is mostly GUI and it shows data that is written to an xml file from a c++ command line tool. Now I want to add a button to the java program to refresh the data. This means that my program has to call the c++ functionality.

Is the best way to just call the program from java through a system call? The c++ program will be compiled for mac os and windows and should always be in the same directory as the java program.

I would like to generate an executable can the c program be stored inside the jar and called from my program?


回答1:


Assuming no better communication method is available (SOAP, ICE, Sockets, etc), I'd call the executable using Runtime.exec(). JNI can be used to interface directly, but I wouldn't recommended it. No you can't put an executable in the jar. Well you can, but you can't run it, since the shell doesn't know how to run it.




回答2:


If you have access to the code and want an 'interactive' experience with the external program (e.g., make call, get results, make additional calls), investigate JNI, which allows you to call C or C++ code from a Java application by including & linking JNI juice to your C or C++ app with .

See:

http://en.wikipedia.org/wiki/Java_Native_Interface

http://www.acm.org/crossroads/xrds4-2/jni.html

If you really just need a "launch app and get results" sort of solution, check out Runtime.exec(), which lets you launch an external program & capture its output.

See: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

http://www.rgagnon.com/javadetails/java-0014.html




回答3:


You may also want to look at the Java Native Access API (JNA).




回答4:


To answer your final question, you can't run an executable from within your jar.

However, you can store it within your jar and extract it to a temporary directory/file prior to running it (check for its presence the first time and extract if necessary). This will simplify your distribution somewhat, in that you only have the jar to distribute, and ensures that you're running an executable that matches your jarred Java code.



来源:https://stackoverflow.com/questions/1210115/how-to-call-c-functionality-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!