Friday, April 19, 2013

jni jnienv DefineClass example c c++ java


DefineClass


jclass DefineClass(JNIEnv *env, const char *name, jobject loader,
const jbyte *buf, jsize bufLen);

Loads a class from a buffer of raw class data. The buffer containing the raw class data is not referenced by the VM after the DefineClass call returns, and it may be discarded if desired.
LINKAGE:
Index 5 in the JNIEnv interface function table.
PARAMETERS:

env: the JNI interface pointer.
name: the name of the class or interface to be defined. The string is encoded in modified UTF-8.

loader: a class loader assigned to the defined class.

buf: buffer containing the .class file data.

bufLen: buffer length.

RETURNS:

Returns a Java class object or NULL if an error occurs.

THROWS:

ClassFormatError: if the class data does not specify a valid class.

ClassCircularityError: if a class or interface would be its own superclass or superinterface.

OutOfMemoryError: if the system runs out of memory.

SecurityException: if the caller attempts to define a class in the "java" package tree.
Example - DefineClass
#include<jni.h>
#include<ls_TestClassLoader.h>
#include<iostream>

using namespace std;
//JNIEnv *, jobject, jstring, jbyteArray, jint
JNIEXPORT jclass JNICALL Java_ls_TestClassLoader_defineClassX(JNIEnv *env, jobject obj, jstring name, jbyteArray data, jint len) {
    JNIEnv &e=*env;
    jboolean isCopy;
    jclass cls= e.DefineClass(e.GetStringUTFChars(name,&isCopy),obj,e.GetByteArrayElements(data,&isCopy),500);
    return cls;
}