我刚刚开始了一项新工作。这里我们是使用JNI(桥接C++/Java)的新手。我是JNI的新手,所以请原谅我的noobness :)JNI与C++对象实例
在我们的(win32)Java应用程序中,我们正在加载一个C++ DLL。在Java方面,我们有几个“SomeJClass”实例,每个实例都需要访问DLL端的“SomeCClass”的相应实例。 该DLL公开入口点,如GlobalDoSomethingInC()。在这里我必须调用Doer :: DoSomethingInC()的实例方法。所以我需要一个平滑的方式来映射相应的这个指针。 当DLL线程发现一些有趣的事情需要通知相应的Java实例时,我也需要做同样的映射。
我可以想到几种解决方案,但我不太喜欢它们。我的问题是,有没有比这更好的方法?
1 Java调用C:GetNewInstance()。这将返回一个实际上是指向新C实例的指针的int。 Java将其存储在m_myCInstance中。然后Java调用GlobalDoSomethingInC(),和 1A
// DLL global
void GlobalDoSomethingInC()
{
// retrive this pointer
//calling back to Java:
jobj tmpJ = NewGlobalRef(env, obj);
Doer* myDoer = <reinterpret_cast>(Doer)tmpJ->GetMyCInstance();
myDoer->DoSomething();
DeleteGlobalRef(env, tmpJ);
// Arrrrgh
}
1b或:
// for **every call** that Java adds a parameter,
//which is the stored int:m_myCInstance, and
Doer* myDoer = <reinterpret_cast>(Doer)instanceParam->DoSomethingInC();
// Can we do better that this?
2对于从C到Java的调用,事情看起来,也许,更好
In the constructor C calls back into Java and stores
the Java instance reference
in a member variable. m_myJInstance.
In all subsequent calls m_myJInstance can be used to call back Java.
In the destructor we need to call DeleteGlobalRef(env, m_myJInstance);
不是太不好,我想。但是存储jobject引用真的很安全。 我的意思是:当GC移动物体时会发生什么?
3我们现在的解决方案“工作”。但它属于上,而在http://www.codinghorror.com/blog/ :)
感谢名单