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


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?


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);  


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()  


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.


var pointer = new IntPtr(&myVariable);  

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