Search code examples
c#vb.netpointersunsafe

How do I get a fixed pointer to a MemoryStream?


I have a memorystream object to which I need a fixed pointer (I am using VB.net, I think this equates to IntPtr). I need this because a pointer (IntPtr) is required as input parameter to another function (that I cannot modify).

I have not worked with unsafe code before and I understand that this might be required. I could switch to C# if required.

I read here (https://www.c-sharpcorner.com/article/pointers-in-C-Sharp/) that "We can say that pointers can point to only unmanaged types which includes all basic data types, enum types, other pointer types and structs which contain only unmanaged types."

This explains why wrapping the memorystream in a struct and using the below code did not work (myTest is a struct that contains the memorystream)

Dim gcHandle As GCHandle = GCHandle.Alloc(myTest, GCHandleType.Pinned)
Dim thePointer As IntPtr = Marshal.ReadIntPtr(GCHandle.ToIntPtr(gchandle))

So my question is how can I get a fixed pointer to my memorystream object with VB.net (preferred) or C#? I am using .NET Framework 4.7.2.


Solution

  • Here is the code that I used based on the input in the comments:


    Dim bytes As Byte() = MyMemoryStream.ToArray()
    Dim gcHandle As GCHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned)
    Dim myPointer As IntPtr = gcHandle.AddrOfPinnedObject()
    

    Basically you have to convert the memorystream to a byte array. You can then pin this array and get a pointer to it.

    Thanks again to all the commenters!