JNI 到 运行 进程而不是使用库
JNI to running process instead of using a library
我有一些图像识别软件运行 为我的游戏生成输入。
我通过 C++ 中的 openCV 检测运动,但是一个限制是游戏本身应该用 java.I 编写,想查询 openCV 进程的状态以获得一些输入对象。我想通过 JNI 调用我的 运行 进程来完成此操作,但所有 JNI 示例都只是调用库函数,而不是 运行 进程。那么这可以通过 JNI 实现还是我必须为此使用套接字?
您可以从 C++ 调用 JVM,初始化基于 openCV 的组件,然后 运行 java 代码。
已解释调用的基础知识 here, with a sample snippet. For an example to launch a Java component via a static method, you can look at the code at the end of this SO answer。
最后,为了调用您的 C++ 监控函数,您必须在 java 代码中使用本机方法,并为其注册一个 C++ 函数。然后,此函数可能会访问您在初始化期间准备的所有内容。示例:
在Java中:
class MyTest {
...
public native void doMonitor(); // to be supplied in C++ trhough JNI
}
在 C++ 中,在初始化代码的某处(在启动 Java 代码之前),您必须注册本机方法:
jclass cls2 = env->FindClass("MyTest");
JNINativeMethod methods[] { { "doMonitor", "()V", (void *)&doMonitorCPP } };
if(env->RegisterNatives(cls2, methods, 1) < 0)
{
if(env->ExceptionOccurred())
cerr << " OOOOOPS: exception when registreing natives" << endl;
else
cerr << " ERROR: problem when registreing naives" << endl;
}
doMonitor()
将定义为例如:
void doMonitorCPP(JNIEnv*e, jobject o) {
std::cout << "C++callback activated" << std::endl;
// do what you need to do with openCV.
}
我有一些图像识别软件运行 为我的游戏生成输入。 我通过 C++ 中的 openCV 检测运动,但是一个限制是游戏本身应该用 java.I 编写,想查询 openCV 进程的状态以获得一些输入对象。我想通过 JNI 调用我的 运行 进程来完成此操作,但所有 JNI 示例都只是调用库函数,而不是 运行 进程。那么这可以通过 JNI 实现还是我必须为此使用套接字?
您可以从 C++ 调用 JVM,初始化基于 openCV 的组件,然后 运行 java 代码。
已解释调用的基础知识 here, with a sample snippet. For an example to launch a Java component via a static method, you can look at the code at the end of this SO answer。
最后,为了调用您的 C++ 监控函数,您必须在 java 代码中使用本机方法,并为其注册一个 C++ 函数。然后,此函数可能会访问您在初始化期间准备的所有内容。示例:
在Java中:
class MyTest {
...
public native void doMonitor(); // to be supplied in C++ trhough JNI
}
在 C++ 中,在初始化代码的某处(在启动 Java 代码之前),您必须注册本机方法:
jclass cls2 = env->FindClass("MyTest");
JNINativeMethod methods[] { { "doMonitor", "()V", (void *)&doMonitorCPP } };
if(env->RegisterNatives(cls2, methods, 1) < 0)
{
if(env->ExceptionOccurred())
cerr << " OOOOOPS: exception when registreing natives" << endl;
else
cerr << " ERROR: problem when registreing naives" << endl;
}
doMonitor()
将定义为例如:
void doMonitorCPP(JNIEnv*e, jobject o) {
std::cout << "C++callback activated" << std::endl;
// do what you need to do with openCV.
}