Search code examples
c#pointersunsafe

Can I convert a value of IntPtr to another IntPtr without unsafe in C#?


Suppose I have a IntPtr which was a void** get from native code. When I was going to deference it to a void* equivalence IntPtr I used such code:

unsafe
{
    var innerPtr = (IntPtr)outerPtr.ToPointer();
}

To do this I need to enable the unsafe code. I'm wondering if there is another way to convert this kind of pointers without unsafe?


Update:

Sorry for my question is invalid. The usage of (IntPtr)outerPtr.ToPointer() is meaningless.


Solution

  • (IntPtr)outerPtr.ToPointer() doesn't actually do anything useful, the result still contains the same address.

    If the equivalent of dereferencing a void** to a void* is what you want, you can use Marshal.ReadIntPtr(IntPtr address).