- 使用开源项目Javacpp
- 项目地址 https://github.com/bytedeco/javacpp
- Centos8
- OracleJDK+环境变量。jdk下载链接 https://www.oracle.com/technetwork/java/javase/downloads/index.html
- gcc编译工具,dnf install man-pages 或者 yum install man-pages,输入 gcc -version 出现版本信息即可
- NativeLibrary.h 中的 C++代码
#include#include using namespace std; namespace NativeLibrary { class NativeClass { public: const std::string& get_property() { return property; } void set_property(const std::string& property) { this->property = property; cout << "C++ Received :" << property << endl;} std::string property; }; }
- NativeLibrary.java 中的Java代码
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
@Platform(include="NativeLibrary.h")
@Namespace("NativeLibrary")
public class NativeLibrary {
public static class NativeClass extends Pointer {
static { Loader.load(); }
public NativeClass() { allocate(); }
private native void allocate();
// to call the getter and setter functions
public native @StdString String get_property(); public native void set_property(String property);
// to access the member variable directly
public native @StdString String property(); public native void property(String property);
}
public static void main(String[] args) {
NativeClass l = new NativeClass();
l.set_property("Hello World!");
System.out.println("From C++:"+l.property());
}
}
-
将 javacpp.jar,NativeLibrary.h,NativeLibrary.java 放到同一个目录下
-
运行命令 java -jar javacpp.jar NativeLibrary.java -exec,出现如下信息
文件下出现了编译后的.class文件和.so文件
-
通过 Java -cp 运行,注意指出依赖的Jar包 java -cp .:javacpp.jar NativeLibrary
更多原创 shellfish.top



