How can I pass MemoryStream data to unmanaged C++ DLL using P/Invoke

前端 未结 1 1343
囚心锁ツ
囚心锁ツ 2020-12-19 03:52

I need your help with the following scenario:

I am reading some data from hardware into a MemoryStream (C#) and I need to pass this data in memory to a dll implement

相关标签:
1条回答
  • 2020-12-19 04:05

    If it's just expecting bytes you can read the MemoryStream into a byte array and then pass a pointer to that to the method.

    You have to declare the external method:

    [DllImport("mylibrary.dll", CharSet = CharSet.Auto)]
    public static extern bool doSomething(IntPtr rawData, int dataLength);
    

    Then, read the bytes from the MemoryStream into a byte array. Allocate a GCHandle which:

    Once allocated, you can use a GCHandle to prevent the managed object from being collected by the garbage collector when an unmanaged client holds the only reference. Without such a handle, the object can be collected by the garbage collector before completing its work on behalf of the unmanaged client.

    And finally, use the AddrOfPinnedObject method to get an IntPtr to pass to the C++ dll.

    private void CallTheMethod(MemoryStream memStream)
    {
       byte[] rawData = new byte[memStream.Length];
       memStream.Read(rawData, 0, memStream.Length);
    
       GCHandle rawDataHandle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
       IntPtr address = handle.AddrOfPinnedObject ();
    
       doSomething(address, rawData.Length);
       rawDataHandle.Free();
     }
    
    0 讨论(0)
提交回复
热议问题