Adding a JNI function

Hello,

I am trying to add a simple JNI function call to the androidEmptyExample and it is not working. Can somebody please help me. I will post the code I added.

in OFActivity:

package cc.openframeworks.androidEmptyExample;

public class OFActivity extends cc.openframeworks.OFActivity{
@Override
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  String packageName = getPackageName();
  this.testJNI();
  ofApp = new OFAndroid(packageName,this);
}
public native void testJNI();

main.cpp:

#include "ofMain.h"
#include "ofApp.h"
int main(){
   ofSetupOpenGL(1024,768, OF_WINDOW);
   ofRunApp( new ofApp() );
   return 0;
}
#ifdef TARGET_ANDROID
#include <jni.h>
extern "C"{
   void Java_cc_openframeworks_OFAndroid_init( JNIEnv*  env, jobject  thiz ){
      main();
   }
}
extern "C"{
   void Java_cc_openframeworks_androidEmptyExample_OFActivity_testJNI( JNIEnv*  env, jobject  thiz ){
      int a = 3;
   }       
}
#endif

This is the logcat output i get:
12-29 14:19:24.210: E/AndroidRuntime(3206): FATAL EXCEPTION: main
12-29 14:19:24.210: E/AndroidRuntime(3206): java.lang.UnsatisfiedLinkError: Native method not found: cc.openframeworks.androidEmptyExample.OFActivity.testJNI:()V

Do I have to add something in another file or why is it not working?

Regards,
Karl

Your syntax/naming of the JNI functions appear to be correct. The issue I see is the order in which you are calling them.

Looking deeper at how the OFAndroid(Java)/ofxAndroid(C++) code is linked together, you will find that all the C++ code is compiled into a JNI library, and loaded via OFAndroid’s init function, inside this block that begins here. OFAndroidAppXX is the what your native C++ code compiles into, and is only loaded after you initialize the OFAndroid class.

Therefore, when you attempt to call the .testJNI() function before initializing OFAndroid, it won’t work because the system has no idea what those are at this point in time.

Simply change:

 this.testJNI();
 ofApp = new OFAndroid(packageName,this);

to:

  ofApp = new OFAndroid(packageName,this);
  this.testJNI();

I just tried copy+pasting your code into the blank project, and can replicate the error when doing it the original way, and changing the order appears to fix it.

hope this helps! :slight_smile: