您的位置:首页 > 其它

使用JNA示例

2015-08-10 18:38 330 查看
使用JNA访问advapi32.dll中的GetUserNameA获得系统用户名

1、根据MSDN中关于GetUserNameA这个API函数的描述

[cpp] view
plaincopy

BOOL GetUserName(

LPTSTR lpBuffer, // address of name buffer

LPDWORD nSize // address of size of name buffer

);

GetUserName函数需要两个参数,这两个参数都是指针,第一个指向一个C字符缓存的字符串(C char buffer),第二个指向一个DWORD,根据JNA文档描述,DWORD可以用int对应,而不是long,对于LPDOWD,就应该使用IntByReference类型来对应,byte[] 来映射LPTSTR类型

2、创建Advapi32接口

[java] view
plaincopy

import com.sun.jna.Library;

import com.sun.jna.Native;

import com.sun.jna.ptr.IntByReference;

import com.sun.jna.win32.StdCallLibrary;

public interface Advapi32 extends StdCallLibrary {

Advapi32 INSTANCE = (Advapi32) Native.loadLibrary("advapi32",

Advapi32.class);

boolean GetUserNameA( byte[] name ,IntByReference size);

}

3、创建Demo示例

[java] view
plaincopy

import java.util.Iterator;

import com.sun.jna.Native;

import com.sun.jna.ptr.IntByReference;

import com.sun.jna.win32.StdCallLibrary;

public class Demo {

public static void main(String[] args) {

try {

byte userName[] = new byte[100];

IntByReference size=new IntByReference(100);

boolean bool = Advapi32.INSTANCE.GetUserNameA(userName, size);

System.out.println("Result:"+bool);

String uName = new String(userName);

System.out.println(uName);

} catch (Exception e) {

e.printStackTrace();

}

}

}

4、补充说明

很多本地函数中需要以两种方式提供字符串,一个版本以A结尾(A表示仅为ASCII文本,支持字符char),另一个版本以W(16位Unicode,支持WCHAR)。如果函数没有其中的一个,则通常以宏的形式代表了他们中某一个,具体是哪个就取决于平台了。通常我们一直选择A版本,直到你真正需要unicode支持,那么你就可以选择W版本,通过显式地指定A或W,你就可以得到你所期望的数据。

本地类型和Window类型对照表

Native TypeSizeJava TypeCommon Windows Types
char8-bit integerbyteBYTE, TCHAR
short16-bit integershortWORD
wchar_t16/32-bit charactercharTCHAR
int32-bit integerintDWORD
intboolean valuebooleanBOOL
long32/64-bit integerNativeLongLONG
long long64-bit integerlong__int64
float32-bit FPfloat
double64-bit FPdouble
char*C stringStringLPTCSTR
void*pointerPointerLPVOID, HANDLE, LPXXX
5、相关链接

JNA官方网址https://jna.dev.java.net/
JavaWorld中相关文章
http://www.coderanch.com/t/274642/Other-JSE-JEE-APIs/java/JNA-call-advapi-GetUserName-function
WindowAPI信息
类型对照表

转载于:http://blog.csdn.net/password318/article/details/4392536
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: