[英]Can C++ call Java code?
I know that Java code can call C++ code through JNI. 我知道Java代码可以通过JNI调用C ++代码。 Is it possible, however, to call Java code from C++ again through JNI or with any other method? 但是,是否可以通过JNI或任何其他方法再次从C ++调用Java代码?
Yep you certainly can. 是的,你当然可以。 Here's an example: 这是一个例子:
Here's the java file: 这是java文件:
public class InvocationHelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("Arguments sent to this program:");
if (args.length == 0) {
System.out.println("(None)");
} else {
for (int i=0; i<args.length; i++) {
System.out.print(args[i] + " ");
}
System.out.println();
}
}
}
And heres some C++ that uses it: 还有一些使用它的C ++:
void invoke_class(JNIEnv* env) {
jclass helloWorldClass;
jmethodID mainMethod;
jobjectArray applicationArgs;
jstring applicationArg0;
helloWorldClass = (env)->FindClass("InvocationHelloWorld");
if(! helloWorldClass )
{
std::cerr<<"Couldn't get \"InvocationHelloWorld\""<<std::endl;
return;
}
mainMethod = (env)->GetStaticMethodID(helloWorldClass, "main", "([Ljava/lang/String;)V");
if(! mainMethod )
{
std::cerr<<"Coulnd't get \"InvocationHelloWorld::main\""<<std::endl;
return;
}
applicationArgs = (env)->NewObjectArray(1, (env)->FindClass("java/lang/String"), NULL);
applicationArg0 = (env)->NewStringUTF("From-C-program");
(env)->SetObjectArrayElement(applicationArgs, 0, applicationArg0);
(env)->CallStaticVoidMethod(helloWorldClass, mainMethod, applicationArgs);
}
You can also use SWIG to automatically generate the JNI files. 您还可以使用SWIG自动生成JNI文件。 The setup can be a bit tricky but it's very useful when you have a lot of C++ code to expose 设置可能有点棘手但是当你有大量的C ++代码要公开时它非常有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.