Tutorial :How to call java from C++



Question:

I need to run this line from my c++ program:

java -jar test.jar text1 text2

the java app will give a float value and give it to the c++ program.

How can I do this? I never call a java stuff before from my ms visual studio C++ file.


Solution:1

When I run the java command directly on my command prompt, it works. but when I run the command from the c++ file, the error says "The system cannot execute the specified program" .

here's my code, im using ms visual studio 2005 :

#include "stdafx.h"    #include <conio.h>      int _tmain(int argc, _TCHAR* argv[])  {        float value;        FILE  *child = _popen("java -jar c:\simmetrics_jar_v1_6_2_d07_02_07.jar text1 ssdyr445", "r");      if (fscanf(child, "%f", &value) == 1)           {              fprintf(stdout,"Got Value from simmetrics: %f\n", value);       }      else           {              fprintf(stdout,"ERROR\n");           }      fclose(child);        return 0;  }  


Solution:2

If you want strong coupling use JNI wrapper.


Solution:3

A simple solution is to use popen() and pclose().

The function popen(), forks() and execs() a sub processes. But it attaches the sub-processes standard-in and standard-out the stream object created by popen. Thus writting anything to the stream in the parent sends it to the standard-in of the sub-processes while anything the sub-processes writes to standard-out can be read from the stream by the parent:

double value;  FILE*  child = popen("java -jar test.jar text1 text2", "r");  if (fscanf(child, "%f", &value) == 1)  {      fprintf(stdout,"Got Value: %f\n", value);  }  else  {      fprintf(stdout,"ERROR\n");  }  fclose(child);  


Solution:4

The easiest if You can modify your java code:

write the result to environment variable (pseudo code below):

solution 1. (Write directly to env. in java app.)

java:

...  setenv('ret', somefloatvalue);  ...    exit..  

c++:

system("java -jar test.jar text1 text2")  ...  getenv("ret")  

(I haven't test it, but important here is the context, does system creates another shell (console), if yes, you'll not see those envs, therefore some other spawn method is necessary)

CreateProcess() on windows fork() on linux.

There are also more complex solutions,

  • send some JASON's through the sockets.... etc.
  • Write to text file in java, read in c++.
  • MPI...
  • extreme in this case CORBA ;)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »