Wednesday, April 24, 2013

jni jnienv RegisterNatives example c c++ java


RegisterNatives


jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint nMethods);

Registers native methods with the class specified by the clazz argument. The methods parameter specifies an array ofJNINativeMethod structures that contain the names, signatures, and function pointers of the native methods. (RegisterNatives)The name andsignature fields of the JNINativeMethod structure are pointers to modified UTF-8 strings. The nMethods parameter specifies the number of native methods in the array. The JNINativeMethod structure is defined as follows:
typedef struct { 

    char *name; 

    char *signature; 

    void *fnPtr; 

} JNINativeMethod; 


The function pointers nominally must have the following signature: (RegisterNatives)
ReturnType (*fnPtr)(JNIEnv *env, jobject objectOrClass, ...); 
LINKAGE:
Index 215 in the JNIEnv interface function table.
PARAMETERS of RegisterNatives

env: the JNI interface pointer.

clazz: a Java class object.

methods: the native methods in the class.

nMethods: the number of native methods in the class.

RETURNS of RegisterNatives

Returns “0” on success; returns a negative value on failure.

THROWS:

NoSuchMethodError: if a specified method cannot be found or if the method is not native.
Example of RegisterNatives

static JNINativeMethod methods[] = {
    {"hashCode",    "()I",                    (void *)&JVM_IHashCode},
    {"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
    {"notify",      "()V",                    (void *)&JVM_MonitorNotify},
    {"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
    {"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
    (*env)->RegisterNatives(env, cls,
                            methods, sizeof(methods)/sizeof(methods[0]));
}