如何使用编组从指针读取uint? [英] How do I read a uint from a pointer with Marshalling?
问题描述
我有一个本机方法,该方法需要一个指针才能写出dword(uint).
I have a native method which needs a pointer to write out a dword (uint).
现在我需要从(Int)指针获取实际的uint值,但是Marshal类仅具有方便的方法来读取(带符号)整数.
Now I need to get the actual uint value from the (Int)pointer, but the Marshal class only has handy methods for reading (signed) integers.
如何从指针获取uint值?
How do I get the uint value from the pointer?
我已经搜索了问题(和Google),但找不到真正需要的东西.
I've searched the questions (and Google), but couldn't really find what I needed.
示例(无效)代码:
IntPtr pdwSetting = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(uint)));
try
{
// I'm trying to read the screen contrast here
NativeMethods.JidaVgaGetContrast(_handleJida, pdwSetting);
// this is not what I want, but close
var contrast = Marshal.ReadInt32(pdwSetting);
}
finally
{
Marshal.FreeHGlobal(pdwSetting);
}
本机函数的返回值是0到255之间的双字,其中255为完全对比.
The return value from the native function is a dword between 0 and 255 with 255 being full contrast.
推荐答案
根据您是否可以使用usafe代码,您甚至可以执行以下操作:
Depending on whether you may use usafe code you can even do:
static unsafe void Method()
{
IntPtr pdwSetting = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(uint)));
try
{
NativeMethods.JidaVgaGetContrast(_handleJida, pdwSetting);
var contrast = *(uint*)pdwSetting;
}
finally
{
Marshal.FreeHGlobal(pdwSetting);
}
}
请注意,像这样的C ++函数指针
Note, that a C++ function pointer like
void (*GetContrastPointer)(HANDLE handle, unsigned int* setting);
可以封为
[DllImport("*.dll")]
void GetContrast(IntPtr handle, IntPtr setting); // most probably what you did
但也
[DllImport("*.dll")]
void GetContrast(IntPtr handle, ref uint setting);
可以让您编写类似的代码
which lets you write code like
uint contrast = 0; // or some other invalid value
NativeMethods.JidaVgaGetContrast(_handleJida, ref contrast);
在性能和可读性上都出色.
which is superior in both performance and readability.
这篇关于如何使用编组从指针读取uint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!