简体   繁体   中英

Wrapping a c++ library using jni

I've successfully added a c++ library to the android 2.3.6 source tree. Now i want to wrap my library in order to be used from java I've searched a lot in the net about the steps to do so but almost all the examples i've found are hello world examples and simple ones... From these examples i've understood that i must create a java file calling the native functions that i need with the prefix native ,then generate the headers and implement the c++ file.

But i don't see how can i call my library functions with this manner. what is the connection between these headers and my function..? i am really confused now and i dont know how to start So, i would be thankfull if someone can tell me the step to wrap a c++ library(already integrated in the aosp)

This is quite a complex problem, and probably beyond the scope of a short answer here. The best thing to do, then, would probably be to guide you to some better documents than the ones you have found so far.

This series of blog posts seems particularly helpful: http://thebreakfastpost.com/2012/01/21/wrapping-ac-library-with-jni-introduction/

You may also find a wrapper autogenerator helpful. There is one that I haven't tried here: http://www.teamdev.com/jniwrapper/features/

If I understood your problem:

Let's say you have a c++ library with this method

int cPlusPlusMethod{
  // Your c++ implementation
}

Basically what you have to do is:

  1. Create the java methods that you need

    native int javaMethod();

  2. Follow the steps that you saw in the links you found in order to create a c++ header, you will have something like:

    JNIEXPORT jint JNICALL Java_yourPackageName_yourJavaClass_javaMethod(JNIEnv *);

  3. Now you have a c++ header with the declarations of all the methods that you need. Write a c++ file that implements that header and copy-paste the c++ implementation of the library.

JNIEXPORT jint JNICALL Java_yourPackageName_yourJavaClass_javaMethod(JNIEnv *env){ // Your c++ implementation }

(You will have to include all the needed imports and put the other files of the lib in the 'jni' folder.)

Execute ndk-build from your android project root folder, and that's it.

Maybe this is not the smartest way to do it but at least for me it worked. Obviously this works if you have the library source files, if you are speaking about a static lib, then I'm not able to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM