简体   繁体   English

如何从JNI调用C ++方法

[英]How to call c++ methods from JNI

in Java code: 在Java代码中:

System.loadLibrary("twolib-second");

int  z = add(1, 2);

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

first.cpp: first.cpp:

#include "first.h"

int  first(int  x, int  y) {
    return x + y; }

first.h: first.h:

#ifndef FIRST_H
#define FIRST_H

extern int first(int  x, int  y);

#endif /* FIRST_H */

second.c: second.c:

#include "first.h"
#include <jni.h>

jint
Java_com_example_jniexample_MainActivity_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    return first(x, y);
}

Android.mk: Android.mk:

LOCAL_PATH:= $(call my-dir)

# first lib, which will be built statically
#
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-first
LOCAL_SRC_FILES := first.cpp

include $(BUILD_STATIC_LIBRARY)

# second lib, which will depend on and include the first one
#
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_SRC_FILES := second.c

LOCAL_STATIC_LIBRARIES := libtwolib-first

include $(BUILD_SHARED_LIBRARY)

I keep getting this error: 我不断收到此错误:

/home/username/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld:./obj/local/armeabi/objs/twolib-second/second.o: in function Java_com_example_jniexample_MainActivity_add:jni/second.c:26: /home/username/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../。 ./../../arm-linux-androideabi/bin/ld:./obj/local/armeabi/objs/twolib-second/second.o:在函数Java_com_example_jniexample_MainActivity_add:jni / second.c:26中:

error: undefined reference to 'first' collect2: ld returned 1 exit status make: * [obj/local/armeabi/libtwolib-second.so] Error 1 错误:对“ first” collect2的未定义引用:ld返回1退出状态make: * [obj / local / armeabi / libtwolib-second.so]错误1

you need to use extern "C" to surround the declaration in first.h in order to call func first from second.c. 您需要使用extern“ C”包围first.h中的声明,以便从second.c首先调用func。

I guess this is because your first file is compiled as cpp but second as c. 我猜这是因为您的第一个文件被编译为cpp,而第二个文件被编译为c。 the difference is the name mangling. 区别在于名称改写。 you can call linux bin util command nm to the static lib and object file to list up symbols and see wjere the rob is. 您可以调用linux bin util命令nm到静态库和目标文件中,以列出符号并查看抢劫情况。 i think you will see in the static lib there is a mangled symbol of funcion first; 我想您会首先在静态库中看到一个功能混乱的符号; a unmangled symbol of func in the second.o 第二个中的func完整符号

you will see many many undefined references while programming with ndk. 使用ndk编程时,您会看到许多未定义的引用。 linux bin utils will be nice tool to make life easier. linux bin utils将是使生活更轻松的好工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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