java如何访问WMI查询的数据(通过JNA)SAFEARRAY结果
我使用jna运行WMI查询。
以下代码查询WMI SELECT Caption,Capabilities from Win32_DiskDrive
。Win32\U磁盘驱动器的类型。能力是uint16[]和结果。getValue返回一个SAFEARRAY实例
System.out.println("Var Type(3 expected): " + value.getVarType().intValue());
如果我多次启动进程,则随机返回0或3
System.out.println("Size (>0 expected): " + (value.getUBound(0) - value.getLBound(0)));
是正确的,但是
Object el = value.getElement(0);
失败了
value.accessData();
返回null,这也是意外的,因此我不能使用OaIdlUtil#TopPrimitiveArray(null指针)
不幸的是,代码不起作用,我也不知道会出什么问题。有什么想法吗
enum Win32_DiskDrive_Values {
Caption,
Capabilities
}
public static void main(String[] args) throws IOException, InterruptedException {
try {
WmiQuery<Win32_DiskDrive_Values> serialNumberQuery = new WmiQuery<Win32_DiskDrive_Values>("Win32_DiskDrive", Win32_DiskDrive_Values.class);
Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED);
WmiResult<Win32_DiskDrive_Values> result = serialNumberQuery.execute();
for (int i = 0; i < result.getResultCount(); i++) {
System.out.println(result.getValue(Win32_DiskDrive_Values.Caption, i));
SAFEARRAY value = (SAFEARRAY) result.getValue(Win32_DiskDrive_Values.Capabilities, i);
// According to https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-diskdrive, the type of Capabilities
// should be uint16[] which should be Variant.VT_I2 (2-byte integer)
// however, it is not constant. sometimes it is 0, sometimes Variant.VT_I2 (3);
System.out.println("Var Type(3 expected): " + value.getVarType().intValue());
System.out.println("Size (>0 expected): " + (value.getUBound(0) - value.getLBound(0)));
Object el = value.getElement(0);
System.out.println("Element 0 (!=null expected): " + el);
Pointer pointer = value.accessData();
System.out.println("pointer (!=null expected): " + pointer);
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
Ole32.INSTANCE.CoUninitialize();
}
}
# 1 楼答案
我提交给JNA项目的WMI代码只设置为处理原语值和字符串,而不是数组。您遇到的问题是WMI正在将指针地址返回到数组(VT_empty=0的空数组或VT_I4=3的32位poniter)。但是WMI结果是在迭代之后发布的,因此您不能使用
WmiResult
来获取对象您需要编写自己的代码(使用JNA实现作为起点)以在迭代期间获取
SAFEARRAY
。您asked this question on the JNA website和@matthiasblaesing发布了以下适用于您的用例的代码片段: