【问题标题】:how to access a method of C++ library (DLL) in java如何在java中访问C++库(DLL)的方法
【发布时间】:2013-07-15 06:22:26
【问题描述】:

我有一个 c++ dll 文件。我知道其中使用的方法。我需要从我的 java 代码中调用这些方法。我无权修改 DLL 文件。请为我提供解决方案。

【问题讨论】:

  • 你也可以用谷歌搜索“JNI”。
  • 您不能调用从其他语言导出到 dll 中的 c++ 方法。 C++ 没有标准化的 ABI 以可靠的方式实现这一点。您必须将 C++ 方法“扁平化”为 C 接口。
  • 有什么方法可以将 c++ 方法扁平化为 C 接口,而无需访问 c++ 代码。
  • 使用 JNA 从 java 调用 DLL 方法变得非常容易。请查看与同一主题相关的my earlier posting。如果仍然遇到任何问题,请告诉我

标签: java c++ dll java-native-interface jna


【解决方案1】:

我正是为此目的创建了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!

【讨论】:

  • 干得好!我很高兴知道你的工具 JavaCPP 因为我以前遇到过类似的问题。我会花一些时间来学习它!谢谢!
  • 顺便说一句,鉴于我不知道这个 DLL 的详细信息,JavaCPP 是否可以直接在 java 代码中调用 DLL 文件中的函数。
  • @AnnieKim 我们至少需要头文件和 C++ 编译器,但其他一切都非常自动化。
  • 好的,我明白了。谢谢。
  • @SamuelAudet,我怎样才能让 IDE 自动生成 Java 类 (LegacyLibrary.java)..?我是否错过了您的解释中的某些内容..?
猜你喜欢
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多