简体   繁体   English

如何在C ++和C#之间共享大字节数组

[英]How to share a big byte array between C++ and C#

I need to share a huge (many megabytes) byte array between a C++ program residing in a DLL and a C# program. 我需要在驻留在DLL的C ++程序和C#程序之间共享一个巨大的字节数组(很多兆字节)。

I need realtime performance, so it is very important I can share it between the two in an efficient way, so making a new copy for it in C# every time after the data is manipulated in C++ is not an option, yet the examples I have found so far seems to depend on this. 我需要实时性能,因此非常重要的一点是我必须以有效的方式在两者之间共享它,因此每次在C ++中操作数据后都无法在C#中为其创建新副本,但是我拥有的示例到目前为止发现的似乎依赖于此。

Is it possible to share the array in an efficient way? 是否可以有效地共享阵列? And if so, how? 如果是这样,怎么办?

In current versions of .NET, any multi-megabyte array will end up on the large object heap and never move. 在当前版本的.NET中,任何多兆字节的数组都将终止在大对象堆上,并且永远不会移动。 However, to be safe, you should pin the array as fejesjoco said. 但是,为了安全起见,您应该按照fejesjoco所说的那样固定阵列。 Then the C++ code can save a pointer into the .NET array and update it in-place. 然后,C ++代码可以将指针保存到.NET数组中并就地更新它。

Use memory mapped file. 使用内存映射文件。 System.IO.MemoryMappedFiles in .NET and CreateFileMapping in C++. .NET中的System.IO.MemoryMappedFiles和C ++中的CreateFileMapping。

Does the .NET marshaler pass a copy, not a reference? .NET封送拆收器是否传递副本而不是引用? If so, then call GCHandle.Alloc(array, GCHandleType.Pinned), then you can get the address of this pinned object and pass that to the DLL as a pointer. 如果是这样,则调用GCHandle.Alloc(array,GCHandleType.Pinned),则可以获取此固定对象的地址并将其作为指针传递给DLL。

In vb.net, I've accomplished this by passing a reference to the first byte. 在vb.net中,我通过将引用传递给第一个字节来实现此目的。 There's no type-checking to ensure that what's passed is really an array of the proper size, but as long as the routine is running the array will be pinned. 没有类型检查可以确保传递的内容确实是一个适当大小的数组,但是只要例程正在运行,该数组就会被固定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM