我正是为此目的创建了JavaCPP。我将从页面中复制/粘贴一些示例代码和解释:
最常见的用例涉及访问一些为 C++ 编写的遗留库,例如,在包含此 C++ 类的名为 LegacyLibrary.h 的文件中:
#include <string>
namespace LegacyLibrary {
class LegacyClass {
public:
const std::string& get_property() { return property; }
void set_property(const std::string& property) { this->property = property; }
std::string property;
};
}
要使用 JavaCPP 完成这项工作,我们可以轻松地定义一个像这样的 Java 类——尽管可以使用 Parser 从头文件中生成它,如下所示:
import com.googlecode.javacpp.*;
import com.googlecode.javacpp.annotation.*;
@Platform(include="LegacyLibrary.h")
@Namespace("LegacyLibrary")
public class LegacyLibrary {
public static class LegacyClass extends Pointer {
static { Loader.load(); }
public LegacyClass() { 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()
LegacyClass l = new LegacyClass();
l.set_property("Hello World!");
System.out.println(l.property());
}
}
或者,我们可以通过使用如下配置类解析头文件来生成 Java 接口:
@Properties(target="LegacyLibrary", value=@Platform(include="LegacyLibrary.h"))
public class LegacyLibraryConfig implements Parser.InfoMapper {
public void map(Parser.InfoMap infoMap) {
}
}
以及以下构建命令:
$ javac -cp javacpp.jar LegacyLibraryConfig.java
$ java -jar javacpp.jar LegacyLibraryConfig
$ javac -cp javacpp.jar LegacyLibrary.java
$ java -jar javacpp.jar LegacyLibrary
如需更复杂的示例,包括 Maven/IDE 集成,请查看JavaCPP Presets!