我有以下 getmacip.cpp
文件,其中包含以下代码片段
// ...code
#include "test.h"
// ...code
Test obj;
obj.printDem();
// ...code
这里是test.h
文件
#ifndef TEST_H
#define TEST_H
class Test
{
public:
void printDem();
};
#endif
这里是test.cpp
文件
#include <iostream>
using namespace std;
void printDem()
{
cout << "deus.ex.machina." << endl;
}
我通过 jni 同时使用 java 和 c++。我已经让文件 getmacip.cpp 与 java 一起工作,如您所见,我正在尝试从 getmacip.cpp 文件中调用 printDem() 方法。我首先使用以下内容编译 getmacip.cpp:
g++ -fPIC -o libgetmacip.so -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux getmacip.cpp -lc
这很好用。然而,当我对 test.cpp 执行相同操作并运行程序时,我得到了错误
/usr/lib/jvm/java-8-oracle/bin/java: symbol lookup error: /home/karl/workspace/sslarp/lib/libgetmacip.so: undefined symbol: _ZN4Test8printDemEv
我显然错误地链接了文件!
最佳答案
printDem()
的定义不属于类 Test
。
使用
#include <iostream>
#include "test.h"
using namespace std;
void Test::printDem() {
cout << "deus.ex.machina." << endl;
}
您还应该链接
方法definition进入共享库,像这样:
g++ -fPIC -o libgetmacip.so \
-shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux \
detmacip.cpp test.cpp
我还应该提到原始 JNI 是一个纯 C 接口(interface),所有 native 调用都是对函数执行的 声明 作为 C 函数(它们的实现可能使用 C++, check this tutorial 。还有 SWIG 项目可以帮助自动{g,t}地为 C++ 创建所需的包装器。
关于java - 在另一个链接/使用 .so 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27208123/