Tuesday, April 17, 2012

Underscores in JNI method names

They say you can use javah to find out the proper C name that corresponds to your Java native method. But I'm not sure how to get that to work, as I'm using Android and javah doesn't recognize the Android symbols such as android.graphics.Bitmap.

Luckily, you don't really need javah because the name is predictable. For example, the Java code
package com.foo;
public MyCode {
public static native int staticFunc(int x, int y);
public native void nonStaticFunc(int x, int y);
Requires C functions like these:
JNIEXPORT int JNICALL Java_com_foo_MyCode_staticFunc(JNIEnv *env, jclass jClass, int x, int y)
{ ... }
JNIEXPORT void JNICALL Java_com_foo_MyCode_nonStaticFunc(JNIEnv *env, jobject self, int x, int y)
{ ... }

I noticed one caveat. If your Java function is declared with an underscore, then the underscore must become "_1" on the C side. Weird eh? It's like this:
public static native int static_func(int x, int y);
JNIEXPORT int JNICALL Java_com_foo_MyCode_static_1func(JNIEnv *env, jclass jClass, int x, int y)
Probably this means you just won't use underscores. This and other weird rules are described here.

I heard a rumor that Android used to require you to define a JNI_OnLoad function which provides a list of your JNI functions. Luckily, this is no longer required.


At 8/22/2013 12:47 PM, Anonymous AD said...

Awesome! This is just what I needed to solve my problem.

I guess the number is used because no C function name can start with a number. I wonder why they did it this way...

Thanks so much!


At 9/03/2013 12:07 AM, Blogger Naveen said...

Thanks. The _1 trick did solve my issue also,


Post a Comment

<< Home