在JNA中,GlobalAlloc和GlobalLock的返回值有什么不同
What is the difference of return value between GlobalAlloc And GlobalLock in JNA
当我使用jna时,GlobalAlloc和GlobalLock都会返回Pointer,但我发现它们的表现好像不相等。
例如,
在下面的这个案例中,我发现TestStructure的实例是没有达到我所期望的状态。
Kernel32 kernel32 = Native.loadLibrary("kernel32",Kernel32.class);
Pointer pointer = kernel32.GlobalAlloc(ghnd, size);
Pointer pointer2 = kernel32.GlobalLock(pointer);
pointer2.write(0, testbyte, 0, dmSize);
TestStructure structure = new TestStructure(pointer);
但下面的情况很好。
Kernel32 kernel32 = Native.loadLibrary("kernel32",Kernel32.class);
Pointer pointer = kernel32.GlobalAlloc(ghnd, size);
Pointer pointer2 = kernel32.GlobalLock(pointer);
pointer2.write(0, testbyte, 0, dmSize);
TestStructure structure = new TestStructure(pointer2);
为什么我必须使用pointer2实例来创建TestStructure。我认为指针和指针2应该指向同一个位置。
//添加2015.04.03
1是的,我在Windows平台上工作。
2测试结构见下文。
public class TestStructure extends Structure {
public char[] dmDeviceName = new char[32];
public WORD dmSpecVersion;
public WORD dmDriverVersion;
public WORD dmSize;
public WORD dmDriverExtra;
public DWORD dmFields;
public UnionField1 unionField1;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
public char[] dmFormname = new char[32];
public WORD dmLogPixels;
public DWORD dmBitsPerpel;
public DWORD dmPelsWidth;
public DWORD dmPelsHeight;
public UnionField2 unionField2;
public DWORD dmDisplayFrequency;
public TestStructure(Pointer pointer) {
useMemory(pointer);
read();
}
@Override
protected List getFieldOrder() {
return Arrays.asList(new String[] { "dmDeviceName", "dmSpecVersion", "dmDriverVersion", "dmSize",
"dmDriverExtra", "dmFields", "unionField1", "dmColor", "dmDuplex", "dmYResolution", "dmTTOption",
"dmCollate", "dmFormname", "dmLogPixels", "dmBitsPerpel", "dmPelsWidth", "dmPelsHeight", "unionField2",
"dmDisplayFrequency" });
}
}
我假设您在Windows平台上工作。GlobalXx
函数实际上是对旧的16位Windows的回忆。在那个(旧)时代,GlobalAlloc
用来返回一个(16位)句柄,该句柄是GlobalLock
转换为32位指针的。
如果您使用GHND=0x42作为第一个参数来请求一个可移动的内存块,您仍然可以表现出类似的行为。如果执行GlobalAlloc
,则返回一个(32位)句柄,该句柄必须转换为具有GlobalLock
的真指针。可以在对GlobalLock
-GlobalUnlock
的不同调用之间为存储器块分配不同的指针值。
MSDN中的页面状态注意全局函数比其他内存管理函数具有更大的开销和更少的功能。新的应用程序应该使用堆函数,除非文档说明应该使用全局函数这意味着MicroSoft建议使用HeapAlloc
系列函数,除非您需要使用GlobalAlloc
。
MSDN中的参考文献:GlobalAlloc函数比较内存分配方法
相关文章:
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 使用 Google 基准测试时返回值会发生什么情况?
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- CUDA返回值错误35的含义是什么
- 是什么意思,返回值是一个类名,后跟一对空括号
- "警告:并非所有控制路径都返回值"是什么意思?(C++)
- 为循环中多次调用的函数返回值预分配内存的正确方法是什么
- 如果我不将其存储在任何地方,返回值会发生什么情况?
- C++ - 在线程中使用时,将函数的返回值声明为 void/void* 之间有什么区别吗?
- memset() 返回值有什么用?
- 从 boost::algorithm::join 返回值的范围是什么?
- 返回值和副作用编码之间有什么区别
- int main() 的返回值是什么意思,如何显示它?
- 在JNA中,GlobalAlloc和GlobalLock的返回值有什么不同
- 当函数返回值是指针,而返回类型是c++中的引用时会发生什么
- GTIFWriteKeys和GTIFKeySet libgeotiff函数(C++)的返回值表示什么
- rdstate() 返回值是什么意思
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- strcmp的返回值是什么意思