[ Followup set ]
On Fri, 15 Oct 2004 15:16:09 -0400, Thomas Smith wrote:
I am building a binding to a runtime engine that was written in C++.
I have no problems setting up the mapping from object calls to the
native implementation, and storing reference to those objects. The
problem comes when I start a new thread... The new thread does not
have access to the same memory, and I end up with a pointer to dead
space.
Please don't multipost.
Two important things to keep in mind:
- the JNIEnv* pointer is only valid in the thread for which it was
created. Whenever you make normal calls from Java to C, you get a
new, valid JNIEnv*. Don't attempt to store the pointer for use in
any other context. If you have created threads in the native code
and need to use JNI functions, use JNI_GetCreatedJavaVMs() and
AttachCurrentThread() to get a valid JNIEnv* for each thread that
needs one.
- when you store object references that will live across multiple
native calls, it is important to only store _global_ references
created with NewGlobalRef(). The JVM doesn't know what your native
variables contain, only what gets passed in and out of your native
code. When you return from a native call, the JVM releases any local
references you held during the call, so there is a risk that such
objects will become eligible for garbage collection unless you
create global references. Don't forget to delete any global
references when you're done with them or they will never become
eligible for garbage collection.
/gordon
--
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e