how to get access to JNIEnv from elsewhere

2,702 views
Skip to first unread message

guich

unread,
Jan 15, 2010, 1:13:47 PM1/15/10
to android-ndk
Hi,

Is there any ways to get access to a valid JNIEnv variable from
somewhere in the C program?

What i do currently is, each time a native method is called, store the
JNIEnv in a global variable and then it this variable elsewhere.
However, if i create a pthread and, from this pthread try to access
the JNIEnv, the application blows up.

Is there a function that could get access to a valid JNIEnv that we
could use to call a static method of a class?

many thanks

guich

Roderick Colenbrander

unread,
Jan 15, 2010, 1:41:14 PM1/15/10
to android-ndk
> What i do currently is, each time a native method is called, store the
> JNIEnv in a global variable and then it this variable elsewhere.
> However, if i create a pthread and, from this pthread try to access
> the JNIEnv, the application blows up.
>
> Is there a function that could get access to a valid JNIEnv that we
> could use to call a static method of a class?
>

Read: http://android.git.kernel.org/?p=platform/dalvik.git;a=blob_plain;f=docs/jni-tips.html;hb=HEAD

Sharing JNIEnv is not possible. The only thing which you can share is
the JavaVM and if really needed you can get a JNIEnv from it.

Roderick

guich

unread,
Jan 15, 2010, 1:47:08 PM1/15/10
to android-ndk
Thanks, but the link is broken...

guich

fadden

unread,
Jan 15, 2010, 4:39:32 PM1/15/10
to android-ndk
On Jan 15, 10:47 am, guich <guiha...@gmail.com> wrote:
> Thanks, but the link is broken...

Worked for me. It's the "JNI Tips" document in dalvik/docs/jni-
tips.html in the source tree. If you start at the top of the git
tree:

http://android.git.kernel.org/

and then click "tree" on the platform/dalvik.git line, click "tree" on
"docs", and then "raw" on "jni-tips.html", you'll see the doc.

To do what you want, you can store the "JavaVM" in a global, and then
get the per-thread JNIEnv* from vm->GetEnv(). Alternatively, you can
get it as a result of calling vm->AttachCurrentThread(), which is
largely a no-op if the thread is already attached. (And the thread
*must* be attached to perform JNI operations.)

You can get the JavaVM pointer from JNI_OnLoad, from
JNI_GetCreatedJavaVMs(), or by calling env->GetJavaVM from a native
method you call into.

fadden

unread,
Jan 15, 2010, 6:44:20 PM1/15/10
to android-ndk
On Jan 15, 1:39 pm, fadden <fad...@android.com> wrote:
> You can get the JavaVM pointer from JNI_OnLoad, from
> JNI_GetCreatedJavaVMs(), or by calling env->GetJavaVM from a native
> method you call into.

As discussed in another thread: don't use JNI_GetCreatedJavaVMs at
this time.

guich

unread,
Jan 17, 2010, 10:07:20 AM1/17/10
to android-ndk
Hi,

"(And the thread *must* be attached to perform JNI operations.)"

Are you talking about Java or C pthread?

thanks. The tips are really useful.

guich

Reply all
Reply to author
Forward
0 new messages