g++编译动态库。测试java jni调用第三方动态库。[android studio IDE]

来源:互联网 发布:anaconda mac 安装 编辑:程序博客网 时间:2024/06/08 17:28

gcc生成动态库命令。

例如:

Helloworld.h如下:

class Hellworld

{

public :

Helloworld();

int add(int a,int b);

int sub(int a,int b);

private:

int sum;

}

Hellwordl.cpp:

Helloworld::Helloworld():sum(0)

{

}

Helloworld::add(int a,int b)

{

return sum = a+b;;

}

Helloworld(int a,int b)

{

return a-b;

}

在文件目录下输入g++ Helloworld.cpp -fPIC -shared -o libHelloworld.so;

在同目录下生成动态库libHelloworld.so。可在main函数测试如下:

int main(int argh,char *argv[])

{

QCoreApplication a(argh,argv);

QLibrary lib("动态库地址");

lib.load;

if(lib.isload())

{

qDebug()<<"loadSuccess"<<endl;

}

Helloworld *hw = new Helloworld();

int value = hw->add(20,10);//输出30

value = hw->sub(12,6);//输出6

return a.exec();

}


思路:

新建一个JniLibrary.java,生成一个jni形式的头文件和源文件。如下:

public class JniLibrary{

public native int add(int x,int y);

}

头文件如下:

#include <jni.h>

JNIEXPORT jint JNICALL Java_com_example_jnatest_JniLibrary_add(JNIEnv *,object,jint,jint);

源文件如下:

#include <stdio.h>

#include <dlfcn.h>

#include <assert.h>

typedef int (*Add) (int x,int y);

JNIEXPORT jint JNICALL Java_com_example_jnatest_JniLibrary_add(JNIEnv *env,object obj,hint x,hint y)

{

void *handle = dlopen("动态库地址",RTLD_LAZY);

Add add = (Add)dlsym(handle,"add");

assert (add != NULL);

return add(x,y);

}

目前引用dlfcn动态库头文件失败了,导致接口找不到。但是思路应该是正确的。






0 0