利用JNA从Java调用C++
************* 建立VC工程,创建dll *********
--》javaCallCpp.h
extern "C" _declspec(dllexport) void hello();
extern "C" _declspec(dllexport) int add(int first, int second);
--》javaCallCpp.cpp
#include "javaCallCpp.h"
#include <iostream>
int add(int a, int b){
return a+b;
}
void hello()
{
printf("Hello World!\n");
}
************* 建立Java工程,调用dll *********
--》JavaCallCppService.java
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface JavaCallCppService extends Library {
//javaCallCpp.dll 放到工程目录下才行(与.classpath一级),也可以放到C:\WINDOWS\system32下,放到classes下会报找不到库
JavaCallCppService INSTANCE = (JavaCallCppService)Native.loadLibrary("javaCallCpp", JavaCallCppService.class);
public int add(int a, int b);
public void hello();
}
--》JavaCallCppTest.java
public class JavaCallCppTest {
public static void main(String[] args) {
System.out.println(JavaCallCppService.INSTANCE.add(1,2));
JavaCallCppService.INSTANCE.hello();
}
}
************* 需要注意的地方 *********
--》javaCallCpp.dll 放到工程目录下才行(与.classpath一级),也可以放到C:\WINDOWS\system32下,放到classes下会报找不到库;
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'javaCallCpp': 找不到指定的模块。
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:169)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:242)
at com.sun.jna.Library$Handler.<init>(Library.java:140)
at com.sun.jna.Native.loadLibrary(Native.java:368)
at com.sun.jna.Native.loadLibrary(Native.java:353)
at JavaCallCppService.<clinit>(JavaCallCppService.java:5)
at JavaCallCppTest.main(JavaCallCppTest.java:4)
--》在头文件中必须为每个要公开调用的方法声明 extern "C" _declspec(dllexport),否则会java调用报找不到这个函数
参考:http://blog.csdn.net/shadowsick/article/details/9101477#
http://blog.csdn.net/shendl/article/details/3589676/
http://wen866595.iteye.com/blog/974826