使用JNI从Android调用C,只有一个C共享库和头文件

时间:2013-10-25 10:39:53

标签: java android java-native-interface

Android Studio 0.3.1

您好,

我有以下用C语言编写的库,但是没有只有libapp_module.so的源代码

libapp_module.so: ELF 32-bit LSB shared object, ARM, version 1 (SYSV), dynamically linked (uses shared libs), not stripped

我有这个库的头文件:

#ifdef __cplusplus
extern "C" {
#endif

#ifdef _WIN32
#define LIB_API(type) __declspec(dllexport) type
#else 
#define LIB_API(type) type
#endif

LIB_API(int) module_init();

#ifdef __cplusplus
}
#endif

当我尝试从我的Android应用程序调用该函数时,问题是异常:

D/dalvikvm﹕ Added shared lib /data/app-lib/com.sunsystems.snaptest-1/libapp_module.so 0x416f3d88
D/dalvikvm﹕ No JNI_OnLoad found in /data/app-lib/com.sunsystems.snaptest-1/libapp_module.so 0x416f3d88, skipping init
W/dalvikvm﹕ No implementation found for native Lcom/sunsystems/snaptest/App_Module;.module_init:()I
UnsatisfiedLinkError: Native method not found: com.sunsystems.snaptest.App_Module.module_init:()I

这就是我正在做的事情

我创建了一个Android应用程序,我想从我的应用程序调用该module_init(),所以我创建了一个名为App_Module.java的类

public class App_Module {
    /* Load native C libraries */
    static {
        System.loadLibrary("app_module");
    }

    public native static int module_init();
}

我在项目的根目录中使用了这样的JNI:

javah -jni -classpath build/classes/debug -d jni/ com.sunsystems.snaptest.App_Module

生成了以下标题界面:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_sunsystems_snaptest_App_Module */

#ifndef _Included_com_sunsystems_snaptest_App_Module
#define _Included_com_sunsystems_snaptest_App_Module
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_sunsystems_snaptest_App_Module
 * Method:    module_init
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_sunsystems_snaptest_App_Module_module_1init
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

然后在我的Android应用程序中,我在上面的App_Module类中加载库,并像这样调用它:

App_Module.module_init()

所以我猜它在libapp_module.so库中找不到符号。

非常感谢任何建议,

1 个答案:

答案 0 :(得分:1)

您必须实现本机方法并使其调用库中的函数。例如:

#include "header_file_for_your_library.h"

#include "com_sunsystems_snaptest_App_Module.h"

JNIEXPORT jint JNICALL Java_com_sunsystems_snaptest_App_Module_module_1init(JNIEnv *env, jclass klass) {
    return module_init();
}

关于JNI或Android NDK的任何教程都会有更多细节。