I have a native method which needs a pointer to write out a dword (uint).
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.
How do I get the uint value from the pointer?
I've searched the questions (and Google), but couldn't really find what I needed.
Sample (not working) code:
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);
}
The return value from the native function is a dword between 0 and 255 with 255 being full contrast.
You can simply cast it to
uint
:For example:
outputs
4294967295
.Use the Marshal.PtrToStructure overload that takes an IntPtr and a type and pass in typeof(uint) - that ought to work!
Hope this helps!
Depending on whether you may use usafe code you can even do:
Note, that a C++ function pointer like
can be marshaled as
but also as
which lets you write code like
which is superior in both performance and readability.