Tutorial :Getting an IntPtr to a ulong variable in C#



Question:

I need to pass an IntPtr to IStream.Read, and the IntPtr should point to a ulong variable. How do I get this IntPtr that points to my ulong variable?


Solution:1

The best way is to change the IStream definition:

void Read([Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pv,            int cb, /*IntPtr*/ ref int pcbRead);  

Then you can write

int pcbRead = 0;  Read(..., ref pcbRead);  


Solution:2

I believe you have to use the GCHandle method if you want to avoid unsafe code. I am not sure on how this works with boxed value types.

var handle = GCHandle.Alloc(myVar, GCHandleType.Pinned);  var ptr = handle.AddrOfPinnedObject()  


Solution:3

If you cannot use unsafe code try the following.

var myValue = GetTheValue();  var ptr = Marshal.AllocHGLobal(Marshal.SizeOf(typeof(ulong));  Marshal.StructureToPointer(ptr, myValue, false);  

At some point later on, you will need to call Marshal.FreeHGlobal on the "ptr" value.


Solution:4

var pointer = new IntPtr(&myVariable);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »