如何在Android NDK中从C文件调用CPP文件中的函数,反之亦然?

6

我无法在ndk中从c文件调用cpp文件中的函数,也无法从cpp文件调用c文件中的函数。

我已经尝试使用extern "C" {}。

以下是我尝试的代码:

CFileCallingCpp.c:

#include "CFileCallingCpp.h"
//#include "custom_debug.h"
#include "CppFile.h"





void tempFunc() {

}

void printTheLogs() {
    //Its not possible to make use of the CPP class in c file
//  CCustomDebug cls;
//  cls.printErrorLog("This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
//  cls.printErrorLog("EXAMPLE", "This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
    printTheLogs1();
//  tempFunc();
}

CFileCallingCpp.h:

#ifndef _CFILECALLINGCPP_H_
#define _CFILECALLINGCPP_H_

void printTheLogs();


#endif

CppFile.cpp:

#include "CppFile.h"
#include "custom_debug.h"
#include "CFileCallingCpp.h"

void printTheLogs1() {
    CCustomDebug::printErrorLog("This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
    CCustomDebug::printErrorLog("EXAMPLE", "This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
}

#if defined(__cplusplus)
extern "C" {
#endif

void callCFileFunc() {
    printTheLogs();
//  printTheLogs1();
}


#if defined(__cplusplus)
}
#endif

CppFile.h:

#ifndef _CPPFILE_H_
#define _CPPFILE_H_

void printTheLogs1();


#endif

我遇到的错误:

    sh-4.1$ /cygdrive/c/Android/android-ndk/ndk-build
    SharedLibrary  : libJNIExInterface.so
    D:/EclipseWorkspace/NativeExample/obj/local/armeabi/objs-debug/JNIExInterface/CppFile.o: In function `callCFileFunc':
    D:/EclipseWorkspace/NativeExample/jni/CppFile.cpp:15: undefined reference to `printTheLogs()'
    D:/EclipseWorkspace/NativeExample/obj/local/armeabi/objs-debug/JNIExInterface/CFileCallingCpp.o: In function `printTheLogs':
    D:/EclipseWorkspace/NativeExample/jni/CFileCallingCpp.c:18: undefined reference to `printTheLogs1'
    collect2: ld returned 1 exit status
    make: *** [/cygdrive/d/EclipseWorkspace/NativeExample/obj/local/armeabi/libJNIExInterface.so] Error 1
    sh-4.1$

请问有人知道如何在ANDROID-NDK中从c代码调用cpp代码吗?

谢谢,
SSuman185

2个回答

9
如果您在cpp文件中调用一个在c文件中定义的函数,您只需使用。
extern "C" void c_func(); // definition

// from a cpp file
c_func();

您可以反过来做,从C文件中调用在cpp文件中实现的函数。
// implemnatation in cpp file
extern "C" void cpp_func()
{
    // c++ code allowed here
}

// declaration in .h file
#ifdef _CPLUSPLUS
extern "C" void cpp_func();
#else
extern void cpp_func();
#endif

// from the c file
....
cpp_func();
.....

2
extern "C"应该放在被C源文件包含的头文件中,而不是放在C++源文件中。对于被C++源文件包含的C头文件也是同样的道理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接