我想通过JNI从Android使用一个预建的C++库。因此,我正在使用Android Studio。
我正在用com.android.tools.build:gradle-experimental:0.7.0-alpha4构建这个项目,我的build.gradle看起来像这样:
apply plugin: "com.android.model.application"
model {
repositories {
libs(PrebuiltLibraries) {
rexxlib {
binaries.withType(SharedLibraryBinary) {
sharedLibraryFile = file("src/main/jniLibs/armeabi/librexx.so")
}
}
rexxapilib {
binaries.withType(SharedLibraryBinary) {
sharedLibraryFile = file("src/main/jniLibs/armeabi/librexxapi.so")
}
}
}
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "org.oorexx.oorexxforandroid"
minSdkVersion.apiLevel 19
targetSdkVersion.apiLevel 23
versionCode 1
versionName "1.0"
buildConfigFields {
create() {
type "int"
name "VALUE"
value "1"
}
}
}
ndk {
moduleName "rexxwrapper"
}
buildTypes {
release {
minifyEnabled false
proguardFiles.add(file("proguard-rules.pro"))
}
}
// Configures source set directory.
sources {
main {
java {
source {
srcDir "src/main/java"
}
}
jniLibs {
dependencies {
library "rexxlib"
library "rexxapilib"
}
}
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
}我创建了一个包装器C库来从那里调用预构建库。
#include "org_oorexx_oorexxforandroid_jniwrapper_RexxWrapper.h"
#include <jni.h>
JNIEXPORT jstring JNICALL Java_org_oorexx_oorexxforandroid_jniwrapper_RexxWrapper_callrexx(JNIEnv *env, jobject instance) {
//TODO: call function of prebuilt library librexx.so - What todo?
return (*env)->NewStringUTF(env, "Hello From Jni");
}我的包装器的Java类:
public class RexxWrapper {
private native String callrexx();
static public void execute(String argv[]) {
RexxWrapper rexxWrapper = new RexxWrapper();
System.out.println("--> "+rexxWrapper.callrexx());
}
static {
System.loadLibrary("rexx");
System.loadLibrary("rexxwrapper");
}
}我已经在我的共享库(C++)中创建了一个测试方法,如下所示:
int AndroidRexxStart()
{
return 1;
}一切正常,并且我从我的包装器c库中得到了响应。现在,我想在包装器库中调用预构建库librexx.so的函数AndroidRexxStart(),但我不知道该怎么做。我必须包含什么以及如何调用该方法?
编辑:我的项目结构:

发布于 2016-08-03 21:41:55
您已经为该库创建了一个Java包装器,但您还需要为Java调用一个JNI包装器。因此,对于要调用的每个库方法,都需要使用JNI方法。我不知道LibRexx是什么,所以我不知道你想叫什么,但你只需要在JNI中公开它们,这样就可以从Java中调用它们了。
首先,你的rexxWrapper应该在librexx中链接,所以你不需要在Java中加载它。其次,您可以像这样创建另一个JNI方法:
JNIEXPORT jint JNICALL Java_org_oorexx_oorexxforandroid_jniwrapper_RexxWrapper_start(JNIEnv *env, jobject instance) {
return AndroidRexxStart();
}然后在你的AndroidRexxStart()中,你实际上会调用librexx来启动它。
在Java中,您将添加:
private native String start();调用JNI方法。JNI方法的命名很重要。它必须与您要使用的Java路径、类和方法名相匹配。
https://stackoverflow.com/questions/38745179
复制相似问题