如何从Java访问C ++库(DLL)的方法 [英] how to access a method of C++ library (DLL) 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();
}
}
执行时遇到以下错误:
java -jar dist / accessLibrary.jar
线程main中的异常java.lang.UnsatisfiedLinkError:查询函数'showVersion时出错':找不到指定的程序。
在本机库源代码中,该方法定义如下
void CPlugin :: showVersion(){
/ * ... * /
}
我对Java非常新鲜。可能我错过了一些基本的东西。看到类似的问题,但没有一个解决我的问题。
忘了提到我正在使用Windows 7 64位和Java 7。
首先,您不能导出类方法并将其加载到java中。这个名字会被破坏,java不知道如何调用它。您需要做的是将其独立的分解为单独的函数。
之后:
如前所述,请确保导出该功能。您可以使用两种方式之一导出。第一个是提到的,那就是使用__declspec(dllexport)。第二个是将它放入def文件中。
此外,请确保将其标记为externC,否则名称将被破坏。所有细节都在这里:使用dllexport从DLL导出功能
所以签名应该是这样的:
extern C__declspec(dllexport)void showVersion(){
}
最后,可以在这里下载: http://www.dependencywalker.com/
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.
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/
这篇关于如何从Java访问C ++库(DLL)的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!