how to access a method of C++ library (DLL) from J

2019-01-26 15:50发布

问题:

I have a library which is written in C++ (actually a Firefox plugin, xyz.dll) and I need to access its methods from 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. 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.

回答1:

First, you cannot export a class method and load it into java. The name will get mangled, and java wouldn't know how to call it properly. 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 ). The second is to put it into the def file.

Additionally, make sure you mark it as extern "C" otherwise the name will get mangled. All the details are here: Exporting functions from a DLL with dllexport

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/



回答2:

I think your native library needs to provide a C-style interface, for example

__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.



标签: java dll