none
How to get back byte[] from (IntPtr referred to byte[]) without marshaling of data? RRS feed

  • Question

  • When I allocate memory in managed area using GCHandle.Alloc + option Pinned, then I block this memory from to be removed by GC. But the object itself stays in managed area. In my case it is byte[] buffer. See the code.

    byte[] buffer;
    buffer = new byte[dwBufferLength];
    GCHandle bufferPin = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    IntPtr lpData = bufferPin.AddrOfPinnedObject();

    How to get back byte[] buffer from lpData(IntPtr)?

    do not understand how

                        unsafe
                        {
                        fixed (byte* p = buffer)
                        { 
                            IntPtr ptr = (IntPtr)p; <-- i Can do that
                            p = (byte*)ptr; <== But i need this... reverse
                        }
                        }

    Literally,

    I have a queue of pointers to buffers, pinned and located inside managed area. I pass these stack of pointers to some API, and inside API they will be filled with some data.

    When I get them back, I want to proceed further with filled buffers in a usual way - like I manage an array of bytes byte[].

    But to do this, I need to convert IntPtr to byte[] in managed area without marshaling of any data. Just to cast it somehow to byte[].

    Pls, any idea?



    • Edited by RobbKirk Wednesday, March 27, 2019 7:13 PM
    Wednesday, March 27, 2019 7:11 PM

Answers

  • Try this:

       IntPtr ptr = . . .;

     

       unsafe

       {

          byte* p = (byte*)ptr.ToPointer();

     

          . . .

       }

     

    Inside this block you can use expressions like p[123], p[i], etc.

     

    • Marked as answer by RobbKirk Wednesday, March 27, 2019 7:58 PM
    Wednesday, March 27, 2019 7:28 PM

All replies

  • Try this:

       IntPtr ptr = . . .;

     

       unsafe

       {

          byte* p = (byte*)ptr.ToPointer();

     

          . . .

       }

     

    Inside this block you can use expressions like p[123], p[i], etc.

     

    • Marked as answer by RobbKirk Wednesday, March 27, 2019 7:58 PM
    Wednesday, March 27, 2019 7:28 PM
  • Thank you!!!
    Wednesday, March 27, 2019 7:58 PM