Take the 2-minute tour ×

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?

share|improve this question
As a side note to people answering this question, he wants a ulong because .NET's IntPtr is 64-bit on x64 systems. –  Powerlord Mar 27 '09 at 14:36
Well, I need a ulong because IStream.Read needs a IntPtr to a ulong. –  Ries Mar 27 '09 at 14:54
add comment

4 Answers

up vote 3 down vote accepted

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);
share|improve this answer
Aftre some thought I realized this was my best option. IStream is after all just an interface. Why not create my own interface... –  Ries Mar 30 '09 at 7:12
add comment

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()
share|improve this answer
This approached worked. Interestingly I still needed to Marshal.WriteInt64 the value back to my ulong variable (perhapsit was just the debugged that was not smart enough though) –  Ries Mar 27 '09 at 14:57
add comment

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.

share|improve this answer
add comment
var pointer = new IntPtr(&myVariable);
share|improve this answer
While this does get the pointer, you haven't asked the GC to keep it fixed, so myVariable may be moved and that pointer no longer belongs to you. –  Samuel Mar 27 '09 at 14:38
add comment

Your Answer


