Created
November 8, 2014 09:19
-
-
Save serkan-ozal/4ec4cbb128645a80ea25 to your computer and use it in GitHub Desktop.
Sample working JNI code to get address of given object, to get object at given address and pin/unpin given object to memory for not to be collected by GC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author SERKAN OZAL | |
* | |
* E-Mail: <a href="mailto:[email protected]">[email protected]</a> | |
* GitHub: <a>https://github.com/serkan-ozal</a> | |
*/ | |
#include <jni.h> | |
#include "tr_com_serkanozal_jvm_playground_MemoryUtil.h" | |
void *p32 = NULL; | |
void *p64 = NULL; | |
JNIEXPORT jobject JNICALL Java_tr_com_serkanozal_jvm_playground_MemoryUtil_pinObject( | |
JNIEnv *env, jclass ownerClass, jobject object) { | |
return (*env)->NewGlobalRef(env, object); | |
} | |
JNIEXPORT void JNICALL Java_tr_com_serkanozal_jvm_playground_MemoryUtil_unpinObject( | |
JNIEnv *env, jclass ownerClass, jobject object) { | |
return (*env)->DeleteGlobalRef(env, object); | |
} | |
JNIEXPORT jlong JNICALL Java_tr_com_serkanozal_jvm_playground_MemoryUtil_getAddress( | |
JNIEnv *env, jclass ownerClass, jobject object, jbyte addressSize) { | |
jlong address = NULL; | |
if (addressSize == SIZE_4_BYTE || addressSize == SIZE_32_BIT) { | |
memcpy(&address, object, SIZE_4_BYTE); | |
} | |
else if (addressSize == SIZE_8_BYTE || addressSize == SIZE_64_BIT) { | |
memcpy(&address, object, SIZE_8_BYTE); | |
} | |
return address; | |
} | |
JNIEXPORT jobject JNICALL Java_tr_com_serkanozal_jvm_playground_MemoryUtil_getObject( | |
JNIEnv *env, jclass ownerClass, jlong address, jbyte addressSize) { | |
void *p = NULL; | |
if (addressSize == SIZE_4_BYTE || addressSize == SIZE_32_BIT) { | |
if (p32 == NULL) { | |
p32 = malloc(SIZE_4_BYTE); | |
} | |
memcpy(p32, &address, SIZE_4_BYTE); | |
p = p32; | |
} | |
else if (addressSize == SIZE_8_BYTE || addressSize == SIZE_64_BIT) { | |
if (p64 == NULL) { | |
p64 = malloc(SIZE_8_BYTE); | |
} | |
memcpy(p64, &address, SIZE_8_BYTE); | |
p = p64; | |
} | |
return (jobject)p; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment