import com.sun.jna.Native;
import com.sun.jna.Platform;
/** Simple example of native library declaration and usage. */
public class HelloWorld {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)
Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, World\n");
for (int i=0;i < args.length;i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
}
3,执行,可以看到控制台中打印出了
Hello, World
但是,请注意,这个程序实际上是使用 msvcrt.dll 这个 C 运行时库中的 printf 函数打印出上
面这些字符的。
看,多简单,不需要写一行 C 代码,就可以直接在 Java 中调用外部动态链接库中的函
数!
例子 2
上面那个例子使用了操作系统自带的动态链接库,现在我们再自己写一个动态链接库试
试。
1,在 VS 中选择 C++语言,然后选择创建一个 Win32 程序。 选择 dll 类型。
2,发布的 C 函数是:
#define MYLIBAPI extern "C" __declspec( dllexport )
MYLIBAPI void say(wchar_t* pValue);
这个函数的实现是:
void say(wchar_t* pValue){
std::wcout.imbue(std::locale("chs"));
std::wcout<<L"上帝说:"<<pValue<<std::endl;
}
它需要传入一个 Unicode 编码的字符数组。然后在控制台上打印出一段中文字符。
3,生成 dll。然后把生成的 dll 文件复制到 Eclipse 项目中,放在项目下面。
4,在 Eclipse 中编写以下代码:
import com.sun.jna.Library;
import com.sun.jna.Native;
评论5