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?

Was it helpful?

Solution

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

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top