You can use the hash table to store pointers and return the key of this hash table to the user. How:
std::unordered_map<long, Foo*> handles; long newHandle = 0 ... JNIEXPORT jlong JNICALL Java_Foo_create (JNIEnv *, jobject) { Foo* ptr = new Foo; long handle = newHandle; handles.insert(std::pair<long, Foo*>(newHandle++, ptr)); return handle; }
Now you can use the handle to get the pointer from the hash map:
JNIEXPORT void JNICALL Java_Foo_use (JNIEnv *, jobject, jlong handle) { auto iter = handles.find(handle); if (iter != handles.end()) { Foo* ptr = iter->second;
Also this method will help you check if the object has already been deleted or delete all Foo objects that still exist. The downside is that accessing the hashmap to get a pointer can slow performance. In addition, you should probably protect your descriptor card from multi-threaded access or use a realistic implementation of the card.
Alternatively, if you need to implement shells for Java, I would recommend considering SWIG (simplified simplifier and interface generator).
Ivan Mushketyk
source share