[英]how to access a method of C++ library (DLL) in java
我有一個c ++ dll文件。 我知道它中使用的方法。 我需要從我的java代碼中調用這些方法。 我沒有權限修改DLL文件。 請給我一個解決方案來做到這一點。
我完全為此目的創建了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預設 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.