我如何使用P / Invoke的MemoryStream数据传递到非托管C ++ DLL [英] How can I pass MemoryStream data to unmanaged C++ DLL using P/Invoke

查看:340
本文介绍了我如何使用P / Invoke的MemoryStream数据传递到非托管C ++ DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以下情形的帮助:

I need your help with the following scenario:

我读从硬件的一些数据到MemoryStream(C#),我需要在内存中通过这个数据(使用指针?)在非托管C ++实现的DLL。
读取(进入流)的数据量非常大(兆字节)。我知道我可以P / Invoke这个dll但我不知道是怎么传流数据的C ++ API的指针/引用?

I am reading some data from hardware into a MemoryStream (C#) and I need to pass this data in memory to a dll implemented in unmanaged C++ (using pointer ??). The data read (into stream) is very large (megabytes). I understand that I can P/Invoke this dll but what I am not sure is how to pass the pointer / reference of the stream data to the C++ API ?

我必须承认我很困惑,我是新的C# - 做我需要使用不安全/固定的,因为数据是大是这些都是无关紧要的MemoryStream的对象由管理GC ?一些示例代码/详细描述将是非常有益的。谢谢

I must admit I am confused as I am new to C# - do I need to use unsafe / fixed since data is large or these are irrelevant as MemoryStream object is managed by GC ? Some example code / detailed description would be very helpful. Thanks

签名:

BOOL DoSomething的(无效* RAWDATA,INT DATALENGTH)

BOOL doSomething(void * rawData, int dataLength)

推荐答案

如果它只是希望字节就可以读取的MemoryStream成字节数组,然后传递一个指针的方法。

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.

您必须声明外部方式:

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



然后,阅读从MemoryStream的字节到字节数组。分配的GCHandle 其中:

分配后,您可以使用一个的GCHandle
,以防止
管理对象被垃圾
收集器时不接受管理的客户端$收集b $ b就掌握的唯一参考。如果没有这样的$ B $巴手柄,该对象可以通过前
中的垃圾收集器完成代表
管理的客户端的工作被收集

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.

最后,使用AddrOfPinnedObject方法来获取一个IntPtr传递给C ++ DLL。

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();
 }

这篇关于我如何使用P / Invoke的MemoryStream数据传递到非托管C ++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆