gpt4 book ai didi

java - 如何在java中访问C++库(DLL)的方法

转载 作者:行者123 更新时间:2023-11-30 01:58:16 24 4
gpt4 key购买 nike

我有一个 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 类,例如这个——尽管可以使用解析器从头文件中生成它,如下所示:

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 接口(interface),例如:

@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 !

关于java - 如何在java中访问C++库(DLL)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17647899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com