how do I run a java program from a c program?

不打扰是莪最后的温柔 提交于 2019-12-10 12:34:08

问题


I have googled for this, but the results are either 10+ years old and do not explain what JNI is or if it is the only approach, or the results are for C++ or C#. So here is my question:

How do I run a Java program from a C program, using the following code as an example? What specific changes to I make to the following code to get the C program to successfully call the java program with parameters?

In the CentOS terminal, I am able to successfully run a java program when I type the following in the command line:

java -cp . my.package.SomeClass 1 2 3

Similarly, from the same folder in the terminal, I am able to successfully run a C program when I type the following in the command line:

./hello  

The code for hello.c is:

#include <stdio.h>

main() {
    printf("Hello World from C!\n");
}  

How do I modify the code for hello.c so that it also runs my.package.SomeClass with the parameters 1 2 3 ?

For example, how do I accomplish the following, but without throwing errors:

#include <stdio.h>

main() {
    printf("Hello World from C!\n");
    java -cp . my.package.SomeClass 1 2 3  //What is the right syntax here?
}  

EDIT

For the sake of future readers of this, and to avoid redundant postings, please also state in your answer how to call a method, such as SomeClass.someMethod(1,2,3);


回答1:


If all you want to do is run java -cp . my.package.SomeClass 1 2 3 from your program, you could just use system which runs an external command:

system("java -cp . my.package.SomeClass 1 2 3");

This is the simplest solution, but not very flexible - you can't interact with the Java program apart from giving it arguments, for example.




回答2:


You do need to use JNI (as far as I know). I use the documentation here all the time:

http://docs.oracle.com/javase/7/docs/technotes/guides/jni/

It's a bit terse but it's workable. It handles C and C++. I don't know C#, so I cannot comment on that (although if forced to guess I would say no to C#).

Running your java program from C will require you to start a JVM programmatically using JNI functions, then find your class, then find your method, then call it. There are examples here to get you started:

http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html#wp9502

If you need more help, you might need to find someone who's done it before to walk you through the steps.




回答3:


I believe you are looking for the exec family of functions. Something like,

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
        const char *file = "java";
        const char *arg = "-cp . my.package.SomeClass 1 2 3";
        printf("Hello World from C!\n");
        execlp(file, arg, (char *) NULL);
}


来源:https://stackoverflow.com/questions/32130698/how-do-i-run-a-java-program-from-a-c-program

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