我有一个c ++ dll文件。我知道它中使用的方法。我需要从我的java代码中调用这些方法。我没有权限修改DLL文件。请为我提供解决方案。
答案 0 :(得分:4)
我完全为此目的创建了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!