Showing posts with label jnienv. Show all posts
Showing posts with label jnienv. Show all posts

Wednesday, April 24, 2013

jni jnienv GetJavaVM example c c++ java


GetJavaVM


jint GetJavaVM(JNIEnv *env, JavaVM **vm);

Returns the Java VM interface (used in the Invocation API) associated with the current thread. The result is placed at the location pointed to by the second argument, vm. (GetJavaVM)
LINKAGE:
Index 219 in the JNIEnv interface function table.
PARAMETERS of GetJavaVM

env: the JNI interface pointer.

vm: a pointer to where the result should be placed.

RETURNS of GetJavaVM

Returns “0” on success; returns a negative value on failure.
Example of GetJavaVM
static JavaVM *jvm;
JNIEXPORT void JNICALL Java_SomeClass_init(JNIEnv *env, jclass) {
    int status = (*env)->GetJavaVM(env, &jvm);
    if(status != 0) {
        // Fail!
    }
}
Now you can use that JavaVM* to get the current JNIEnv* with AttachCurrentThread:
dsmResult_t dsmInitializeCall( dsmResult_t status, void * pUserData, dsmEvent_t * hEvent ) {
    JNIEnv *env;
    (*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL);
    (*env)->CallVoidMethod(env, classObject, mid);
}


jni jnienv ToReflectedField example c c++ java


ToReflectedField

jobject ToReflectedField(JNIEnv *env, jclass cls,
   jfieldID fieldID);
Converts a field ID derived from cls to a java.lang.reflect.Field object.
Throws OutOfMemoryError and returns 0 if fails.
LINKAGE:
Index 12 in the JNIEnv interface function table.
Example of ToReflectedField
/*
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and
    limitations under the License.
*/
  
#include <jni.h>

/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.ToReflectedFieldTest.nativeExecute()Ljava/lang/reflect/Field;
 */
JNIEXPORT jobject JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_ToReflectedFieldTest_nativeExecute
    (JNIEnv *env, jobject this_object)
{
 jfieldID fID;
 jclass clazz = (*env)->GetObjectClass(env, this_object);
 if(!clazz) return NULL;
 fID = (*env)->GetStaticFieldID(env, clazz, "staticField", "I");
 return (*env)->ToReflectedField(env, clazz, fID, JNI_TRUE);
}

/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.ToReflectedFieldTest.nativeExecute1()Ljava/lang/reflect/Field;
 */
JNIEXPORT jobject JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_ToReflectedFieldTest_nativeExecute1
    (JNIEnv *env, jobject this_object)
{
 jfieldID fID;
 jclass clazz = (*env)->GetObjectClass(env, this_object);
 if(!clazz) return NULL;
 fID = (*env)->GetFieldID(env, clazz, "objectField", "D");
 return (*env)->ToReflectedField(env, clazz, fID, JNI_FALSE);
}

jni jnienv ToReflectedMethod example c c++ java


ToReflectedMethod

jobject ToReflectedMethod(JNIEnv *env, jclass cls,
   jmethodID methodID);
Converts a method ID derived from cls to a java.lang.reflect.Method or java.lang.reflect.Constructor object.
Throws OutOfMemoryError and returns 0 if fails.
LINKAGE:
Index 9 in the JNIEnv interface function table.
Example of ToReflectedMethod
/*
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and
    limitations under the License.
*/
  
#include <jni.h>

/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.ToReflectedMethodTest.nativeExecute(Ljava/lang/String;)Ljava/lang/reflect/Method;
 */
JNIEXPORT jobject JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_ToReflectedMethodTest_nativeExecute
    (JNIEnv *env, jobject this_object, jstring str)
{
 jmethodID mID;
 jclass clazz;
 jobject ret;

 clazz = (*env)->GetObjectClass(env, str);
 if(!clazz) return NULL;
 mID = (*env)->GetMethodID(env, clazz, "length", "()I");
 if(!mID) return NULL;
 return (*env)->ToReflectedMethod(env, clazz, mID, JNI_FALSE); 
}

/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.ToReflectedMethodTest.nativeExecute1(Ljava/lang/String;)Ljava/lang/reflect/Constructor;
 */
JNIEXPORT jobject JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_ToReflectedMethodTest_nativeExecute1
    (JNIEnv *env, jobject this_object, jstring str)
{
 jmethodID mID;
 jclass clazz;

 clazz = (*env)->GetObjectClass(env, str);
 if(!clazz) return NULL;
 mID = (*env)->GetMethodID(env, clazz, "<init>", "(Ljava/lang/String;)V");
 if(!mID) return NULL;
 return (*env)->ToReflectedMethod(env, clazz, mID, JNI_FALSE); 
}

jni jnienv FromReflectedField example c c++ java


FromReflectedField

jfieldID FromReflectedField(JNIEnv *env, jobject field);
Converts a java.lang.reflect.Field to a field ID.
LINKAGE:
Index 8 in the JNIEnv interface function table.

Example of FromReflectedField


#include <jni.h>
/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.FromReflectedFieldTest.nativeExecute(Ljava/lang/reflect/Field;Ljava/lang/reflect/Field;)Z
 */
JNIEXPORT jboolean JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_FromReflectedFieldTest_nativeExecute
    (JNIEnv *env, jobject this_object, jobject objField, jobject statField)
{
 jfieldID fID_s1,fID_s2,fID_o1,fID_o2;
 jclass cls;

 fID_s1 = (*env)->FromReflectedField(env, statField);
 fID_o1 = (*env)->FromReflectedField(env, objField);
 if(!fID_o1 || !fID_s1) return JNI_FALSE;

 cls  = (*env)->GetObjectClass(env, this_object);
 if(!cls) return JNI_FALSE;
 fID_s2 = (*env)->GetStaticFieldID(env, cls, "staticField", "I");
 fID_o2 = (*env)->GetFieldID(env, cls, "objectField", "D");
 if(!fID_o2 || !fID_s2) return JNI_FALSE;

    if(fID_o1 != fID_o2) return JNI_FALSE;
    if(fID_s1 != fID_s2) return JNI_FALSE;
 return JNI_TRUE;
}

jni jnienv FromReflectedMethod example c c++ java


FromReflectedMethod

jmethodID FromReflectedMethod(JNIEnv *env, jobject method);
Converts a java.lang.reflect.Method or java.lang.reflect.Constructor object to a method ID.
LINKAGE:
Index 7 in the JNIEnv interface function table.

Example of FromReflectedMethod


#include <jni.h>
/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.FromReflectedMethodTest.nativeExecute(Ljava/lang/reflect/Method;)Z
 */
JNIEXPORT jboolean JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_FromReflectedMethodTest_nativeExecute
    (JNIEnv *env, jobject this_object, jobject mRefl)
{
 jmethodID mID1, mID2;
 jclass strClass;

 mID1 = (*env)->FromReflectedMethod(env, mRefl);
 if(!mID1) return JNI_FALSE;

 strClass = (*env)->FindClass(env, "java/lang/String");
 mID2 = (*env)->GetMethodID(env, strClass, "length", "()I");
 if(!mID2) return JNI_FALSE;

 if(mID1 != mID2) return JNI_FALSE;
 return JNI_TRUE;
}

/*
 * Method: org.apache.harmony.vts.test.vm.jni.reflection.FromReflectedMethodTest.nativeExecute1(Ljava/lang/reflect/Constructor;)Z
 */
JNIEXPORT jboolean JNICALL
Java_org_apache_harmony_vts_test_vm_jni_reflection_FromReflectedMethodTest_nativeExecute1
    (JNIEnv *env, jobject this_object, jobject cRefl)
{
 jmethodID mID1, mID2;
 jclass strClass;

 mID1 = (*env)->FromReflectedMethod(env, cRefl);
 if(!mID1) return JNI_FALSE;

 strClass = (*env)->FindClass(env, "java/lang/String");
 mID2 = (*env)->GetMethodID(env, strClass, "<init>", "(Ljava/lang/String;)V");
 if(!mID2) return JNI_FALSE;

 if(mID1 != mID2) return JNI_FALSE;
 return JNI_TRUE;
}

jni jnienv GetDirectBufferCapacity example c c++ java


GetDirectBufferCapacity

jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf);
Fetches and returns the capacity in bytes of the memory region referenced by the given direct java.nio.Buffer.
LINKAGE of GetDirectBufferCapacity
Index 231 in the JNIEnv interface function table.
PARAMETERS of GetDirectBufferCapacity
env: the JNIEnv interface pointer
buf: a direct java.nio.Buffer object (must not be NULL)
RETURNS of GetDirectBufferCapacity
Returns the capacity in bytes of the memory region associated with the buffer. Returns -1 if the given object is not a directjava.nio.Buffer, if the object is an unaligned view buffer and the processor architecture does not support unaligned access, or if JNI access to direct buffers is not supported by this virtual machine.
Example of GetDirectBufferCapacity


public class SomeClass {
    /**
     * @param buffer input/output buffer
     * @return number of bytes written to buffer
     */
    private native int nativeMethod(ByteBuffer buffer);

    public void myMethod() {
        ByteBuffer buffer = ByteBuffer.allocateDirect(100);
        int written = nativeMethod(buffer);
        if (written > 0) {
            buffer.limit(written);
        }
        ...
    }
}
static jint nativeMethod(JNIEnv *env, jobject obj, jobject buffer) {
    jclass cls = env->GetObjectClass(buffer);
    jmethodID mid = env->GetMethodID(cls, "limit", "(I)Ljava/nio/Buffer;");
    char *buf = (char*)env->GetDirectBufferAddress(buffer);
    jlong capacity = env->GetDirectBufferCapacity(buffer);
    int written = 0;

    // Do something spectacular with the buffer...

    env->CallObjectMethod(buffer, mid, written);
    return written;
}

jni jnienv GetDirectBufferAddress example c c++ java


GetDirectBufferAddress

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);
Fetches and returns the starting address of the memory region referenced by the given direct java.nio.Buffer.(GetDirectBufferAddress)
This function allows native code to access the same memory region that is accessible to Java code via the buffer object.
LINKAGE:
Index 230 in the JNIEnv interface function table.
PARAMETERS of GetDirectBufferAddress
env: the JNIEnv interface pointer
buf: a direct java.nio.Buffer object (must not be NULL)
RETURNS of GetDirectBufferAddress
Returns the starting address of the memory region referenced by the buffer. Returns NULL if the memory region is undefined, if the given object is not a direct java.nio.Buffer, or if JNI access to direct buffers is not supported by this virtual machine.
Example of GetDirectBufferAddress
JNIEXPORT jobject JNICALL Java_com_foo_allocNativeBuffer(JNIEnv* env, jobject thiz, jlong size)
{
    void* buffer = malloc(size);
    jobject directBuffer = env->NewDirectByteBuffer(buffer, size);
    jobject globalRef = env->NewGlobalRef(directBuffer);

    return globalRef;
}

JNIEXPORT void JNICALL Java_comfoo_freeNativeBuffer(JNIEnv* env, jobject thiz, jobject globalRef)
{
    void *buffer = env->GetDirectBufferAddress(globalRef);

    env->DeleteGlobalRef(globalRef);
    free(buffer);
}
Then in Java...
mImageData = (ByteBuffer)allocNativeBuffer( mResX * mResY * mBPP );
and
freeNativeBuffer(mImageData);
mImageData = null;

jni jnienv NewDirectByteBuffer example c c++ java


NewDirectByteBuffer

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);
Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes. (NewDirectByteBuffer)
Native code that calls this function and returns the resulting byte-buffer object to Java-level code should ensure that the buffer refers to a valid region of memory that is accessible for reading and, if appropriate, writing. An attempt to access an invalid memory location from Java code will either return an arbitrary value, have no visible effect, or cause an unspecified exception to be thrown.
LINKAGE:
Index 229 in the JNIEnv interface function table.
PARAMETERS of NewDirectByteBuffer
env: the JNIEnv interface pointer
address: the starting address of the memory region (must not be NULL)
capacity: the size in bytes of the memory region (must be positive)
RETURNS of NewDirectByteBuffer
Returns a local reference to the newly-instantiated java.nio.ByteBuffer object. Returns NULL if an exception occurs, or if JNI access to direct buffers is not supported by this virtual machine.
EXCEPTIONS:
OutOfMemoryError: if allocation of the ByteBuffer object fails
Example of NewDirectByteBuffer
JNIEXPORT jobject JNICALL Java_com_foo_allocNativeBuffer(JNIEnv* env, jobject thiz, jlong size)
{
    void* buffer = malloc(size);
    jobject directBuffer = env->NewDirectByteBuffer(buffer, size);
    jobject globalRef = env->NewGlobalRef(directBuffer);

    return globalRef;
}

JNIEXPORT void JNICALL Java_comfoo_freeNativeBuffer(JNIEnv* env, jobject thiz, jobject globalRef)
{
    void *buffer = env->GetDirectBufferAddress(globalRef);

    env->DeleteGlobalRef(globalRef);
    free(buffer);
}
Then in Java...
mImageData = (ByteBuffer)allocNativeBuffer( mResX * mResY * mBPP );
and
freeNativeBuffer(mImageData);
mImageData = null;

jni jnienv MonitorExit example c c++ java


MonitorExit


jint MonitorExit(JNIEnv *env, jobject obj);

The current thread must be the owner of the monitor associated with the underlying Java object referred to by obj.(MonitorExit) The thread decrements the counter indicating the number of times it has entered this monitor. If the value of the counter becomes zero, the current thread releases the monitor.
Native code must not use MonitorExit to exit a monitor entered through a synchronized method or a monitorenter Java virtual machine instruction.
LINKAGE:
Index 218 in the JNIEnv interface function table.
PARAMETERS of MonitorExit

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS of MonitorExit

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

EXCEPTIONS:

IllegalMonitorStateException: if the current thread does not own the monitor.
Example of MonitorExit


JNIEXPORT void JNICALL Java_company_com_HelloActivity_setBuffer(JNIEnv *env, jobject obj, jstring jstr)
{
    char buf[256];

    int len = (*env)->GetStringLength(env, jstr);       
    (*env)->GetStringUTFRegion(env, jstr, 0, len, buf);
    (*env)->MonitorEnter(env, obj); // I don't think this is correct.
    strcat(buffer, buf); // buffer is declared as global char buffer[256];
    (*env)->MonitorExit(env, obj);
}
EDIT: How about this? syncobj is defined in Activity as static Object and shared with another thread.
JNIEXPORT void JNICALL Java_company_com_HelloActivity_setBuffer(JNIEnv *env, jobject obj, jstring jstr, jobject syncobj)
{
    char buf[256];

    int len = (*env)->GetStringLength(env, jstr);       
    (*env)->GetStringUTFRegion(env, jstr, 0, len, buf);
    (*env)->MonitorEnter(env, syncobj);
    strcat(buffer, buf);
    (*env)->MonitorExit(env, syncobj);
}