Skip to content

Instantly share code, notes, and snippets.

@mmoczkowski
Created November 28, 2014 09:09
Show Gist options
  • Save mmoczkowski/11ce500822f355adb309 to your computer and use it in GitHub Desktop.
Save mmoczkowski/11ce500822f355adb309 to your computer and use it in GitHub Desktop.
/* Java class */
public void FooHandler {
private long mHandle; // stores native pointer
/* Creates c++ object and returns it's pointer */
private native long init();
/* Calls "delete" on c++ object */
private native void destroy(long handle);
/* Arbitrary native method */
private native int bar(long handle, int a, float b);
public FooHandler() {
mHandle = init();
if(mHandle == 0) {
throw Exception();
}
}
public void destroy() {
destroy(mHandle);
mHandle = 0;
}
public int bar(int a, float b) {
return bar(mHandle, a, b);
}
}
/* C++ class */
class CFoo {
public:
CFoo() {}
virtual ~CFoo() {}
int bar(int a, float b) { ... }
};
/* JNI part */
jlong com_example_FooHandler_init() {
CFoo* pMyFoo = new CFoo();
return (jlong)pMyFoo; // cast the pointer to jlong
}
void com_example_FooHandler_destroy(jlong handle) {
CFoo* pMyFoo = (CFoo*)handle;
delete pMyFoo;
}
jint com_example_FooHandler_bar(jlong handle, jint a, jfloat b) {
CFoo* pMyFoo = (CFoo*)handle;
return pMyFoo->bar(a, b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment