JavaCPP初体验
背景
JavaCPP库,使用JNI技术,提供了一种高效的Java访问C++的方法。
JavaCPP初体验
先用一个例子,来有个整体的感觉。这个例子中,给出了如何在Java中访问C++的方法。
下载
wget "http://search.maven.org/remotecontent?filepath=org/bytedeco/javacpp/1.4.4/javacpp-1.4.4-bin.zip" -O javacpp-1.4.4-bin.zip
相关文件
NativeLibrary.h
内容如下:
#include
namespace NativeLibrary {
class NativeClass {
public:
const std::string& get_property() { return property; }
void set_property(const std::string& property) { this->property = property; }
std::string property;
};
}
在类NativeClass中,定义了一个property的字符串,及对应的get和set方法。
NativeLibrary.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) {
// Pointer objects allocated in Java get deallocated once they become unreachable,
// but C++ destructors can still be called in a timely fashion with Pointer.deallocate()
NativeClass l = new NativeClass();
l.set_property("Hello World!");
System.out.println(l.property());
}
}
在类NativeLibrary的main方法中,先初始化了NativeClass对象,再对property赋值为Hello World!,最后再对property的值打印了出来。
所以main方法如果可以正常运行,就说明已经调用成功了NativeClass类。
执行
java -jar javacpp-bin/javacpp.jar NativeLibrary.java -exec
结果
javac -cp javacpp-bin/javacpp.jar:/home/note/example1 NativeLibrary.java
Generating /home/note/example1/jnijavacpp.cpp
Generating /home/note/example1/jniNativeLibrary.cpp
Compiling /home/note/example1/linux-arm64/libjniNativeLibrary.so
g++ -I/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.aarch64/include -I/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.aarch64/include/linux /home/note/example1/jniNativeLibrary.cpp /home/note/example1/jnijavacpp.cpp -O3 -s -Wl,-rpath,$ORIGIN/ -Wl,-z,noexecstack -Wl,-Bsymbolic -Wall -fPIC -shared -o libjniNativeLibrary.so
Deleting /home/note/jniNativeLibrary.cpp
Deleting /home/note/example1/jnijavacpp.cpp
java -cp javacpp-bin/javacpp.jar:/home/note/example1 NativeLibrary
Hello World!