Call java class from c++

Feb 28, 2010 at 7:50pm
Hello every body!!
can any body lead me, how can i call Java class from c++ code ??
I just want to run c++ code that cout"its C++" and also call Java class that print out "its Java "

thanks
Feb 28, 2010 at 8:10pm
That's impossible. You can't have a native-code language (that is, one which compiles to native code) and a bytecode language in one file. The C++ program could, however, call Java to tell it to run the .jar file; e.g.
system("java -jar foo.jar");

But system is evil. Are you on windows or UNIX/Linux/BSD/MacOSX? If you're on windows, I won't know how to do this without using system() but if you're using a UNIX clone or a UNIX-like system, I can help you.
Feb 28, 2010 at 8:54pm
It is difficult to do this in the same process space, but easy to do using a distributed system. In a distributed messaging system, the producer puts a message on a message queue (fanout) that is picked up by both a C++ and a Java consumer.

I've done this recently with a Python producer and Java and C++ consumers using Apache Qpid. There is example code provided with the Qpid code that should get you going.

Apache Qpid is just one way to do it. There are many others. And you don't necessarily need a full messaging system. You can do it using raw sockets, xml-rpc, SOAP, CORBA, etc. But a messaging system makes the whole thing a lot easier to manage, especially when the systems get complex.
Feb 28, 2010 at 9:20pm
It's possible.
Look up JNI (Java Native Interface).
Last edited on Feb 28, 2010 at 9:21pm
Feb 28, 2010 at 9:41pm
R0mai, my understanding is that JNI provides access from Java to native libraries (that is, it is Java-centric). Does it also provide access to arbitrary Java classes from C/C++? That would require that there is a native interface to bring up a VM and load a class.

In Python these are distinguished as extending and embedding. Extending allows one to write Python modules in C/C++ (Python is extended with C++ modules). Embedding allows a C/C++ program to bring up a Python VM instance to execute arbitrary Python code (Python is embedded in a C++ program).

Does JNI allowed both extending and embedding? The OP's question would seem to require embedding.

Those limitations and considerations of "who is in control" or "whose main() is called" that exist when trying to make multiple languages work together in one process space just don't exist in distributed systems.
Topic archived. No new replies allowed.