在JNA官网上还介绍了另外一种调用C/C++动态库的方式:直接函数(方法)映射。其编程方法非常简单,连接口定义都免了,只需在类声明中使用关键字native声明动态库的函数,然后在调用动态库的函数之前先调用Native.register方法注册(加载)动态库即可。
* 在JNA官网上还介绍了另外一种调用C/C++动态库的方式:直接函数(方法)映射。
* 其编程方法非常简单,连接口定义都免了,只需在类声明中使用关键字native声明动态
* 库的函数,然后在调用动态库的函数之前先调用Native.register方法注册(加载)动态库即可。
* 说明:该程序既可以在Windows环境下运行也可以在Linux环境下运行。如果是在Windows下,将加载msvcrt.dll动态库;如果是在Linux下,将加载libm.so动态库。
linux和unix的libm.so在/lib/libm.so
在Platform中的代码如下常量:
C_LIBRARY_NAME = osType == WINDOWS ? "msvcrt" : osType == WINDOWSCE ? "coredll" : "c";
MATH_LIBRARY_NAME = osType == WINDOWS ? "msvcrt" : osType == WINDOWSCE ? "coredll" : "m";
package com.etrip.jna.win;
import com.sun.jna.IntegerType;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
/**
*
* @Title: TODO
* @Description: 实现TODO
* @Copyright:Copyright (c) 2011
* @Company:
* @Date:2012-12-22
* @author longgangbai
* @version 1.0
*/
public class CDirectJNA {
static class CLibrary {
public static class size_t extends IntegerType {
public size_t() {
super(Native.POINTER_SIZE);
}
public size_t(long value) {
super(Native.POINTER_SIZE, value);
}
}
public static native Pointer memset(Pointer p, int v, size_t len);
public static native Pointer memset(Pointer p, int v, int len);
public static native Pointer memset(Pointer p, int v, long len);
public static native long memset(long p, int v, long len);
public static native int memset(int p, int v, int len);
public static native int strlen(String s1);
public static native int strlen(Pointer p);
public static native int strlen(byte[] b);
static {
Native.register(Platform.C_LIBRARY_NAME);
}
}
static interface CInterface extends Library {
CInterface instance = (CInterface) Native.loadLibrary(
Platform.C_LIBRARY_NAME, CInterface.class);
Pointer memset(Pointer p, int v, int len);
int strlen(String s);
}
public static void main(String[] args) {
String str="longgangbai";
System.out.println(CLibrary.strlen(str) +" "+CInterface.instance.strlen(str));
}
}
package com.etrip.jna.win;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/**
* @Title: TODO
* @Description: 实现TODO
* @Copyright:Copyright (c) 2011
* @Date:2012-12-22
* @author
* @version 1.0
*/
public class MathDirectJNA {
/**
*通过注册的方式操作cos
*/
static class MathLibrary {
public static native double cos(double x);
static {
Native.register(Platform.MATH_LIBRARY_NAME);
}
}
/**
* 通过jni方式访问操作cos
*/
private static class JNI {
static {
System.load(Platform.MATH_LIBRARY_NAME);
}
private static native double cos(double x);
}
/**
*通过加载的方式操作cos
*/
interface MathInterfaceLibrary extends Library {
MathInterfaceLibrary instance = (MathInterfaceLibrary) Native.loadLibrary(
Platform.MATH_LIBRARY_NAME, MathInterfaceLibrary.class);
double cos(double x);
}
public static void main(String[] args) {
System.out.println(MathLibrary.cos(0.6)+" "+MathInterfaceLibrary.instance.cos(0.6));
}
}
【参考链接】:
https://github.com/twall/jna/blob/master/www/DirectMapping.md