简体   繁体   English

如何从Java访问C ++库(DLL)的方法

[英]how to access a method of C++ library (DLL) from Java

I have a library which is written in C++ (actually a Firefox plugin, xyz.dll) and I need to access its methods from Java. 我有一个用C ++(实际上是Firefox插件xyz.dll)编写的库,我需要从Java访问其方法。

public class AccessLibrary {
    public interface Kernel32 extends Library {
        public void showVersion();
    }

    public static void main(String[] args) {
        Kernel32 lib = (Kernel32) Native.loadLibrary("xyz.dll", Kernel32.class);
        lib.showVersion();
    }
}

While executing got the following error: 执行时出现以下错误:

java -jar dist/accessLibrary.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function  'showVersion': The specified procedure could not be found.

In the native library source code, the method is defined like this 在本机库源代码中,方法定义如下:

void CPlugin::showVersion() {
    /* ... */
}

I am very new to Java. 我对Java非常陌生。 May be I am missing something basic. 可能是我缺少基本的东西。 Looked into similar questions but none of them solves my problem. 调查了类似的问题,但没有一个解决我的问题。

Forgot to mention I am using Windows 7 64bit and Java 7. 忘记提及我正在使用Windows 7 64bit和Java 7。

First, you cannot export a class method and load it into java. 首先,您不能导出类​​方法并将其加载到Java中。 The name will get mangled, and java wouldn't know how to call it properly. 该名称将被修改,而Java将不知道如何正确地调用它。 What you need to do is break it out into a separate function on its own. 您需要做的是将其单独分解为一个单独的功能。

After that: 之后:

As already pointed out, make sure you export the function. 如前所述,请确保导出函数。 You can export using one of two ways. 您可以使用以下两种方法之一进行导出。 The first is what is mentioned, which is to use __declspec( dllexport ). 首先要提到的是使用__declspec(dllexport)。 The second is to put it into the def file. 第二种是将其放入def文件。

Additionally, make sure you mark it as extern "C" otherwise the name will get mangled. 此外,请确保将其标记为extern“ C”,否则名称将被篡改。 All the details are here: Exporting functions from a DLL with dllexport 所有详细信息在这里: 使用dllexport从DLL导出函数

So the the signature should be something like this: 所以签名应该是这样的:

extern "C" __declspec(dllexport) void showVersion () {
}

Finally, the depends tool can be downloaded here: http://www.dependencywalker.com/ 最后,可以在此处下载Depends工具: http : //www.dependencywalker.com/

I think your native library needs to provide a C-style interface, for example 我认为您的本机库需要提供C风格的界面,例如

__declspec( dllexport ) void showVersion() {
  /* ... */
}

Ideally, take a look at your DLL with depends.exe (which is available through the Windows SDK), there you'll see if your DLL provides the correct function exports. 理想情况下,使用depends.exe (可通过Windows SDK获得)查看您的DLL,在那里您将看到您的DLL是否提供了正确的函数导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM