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

独自空忆成欢 提交于 2019-12-10 22:44:01

问题


I need to share a huge (many megabytes) byte array between a C++ program residing in a DLL and a C# program.

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.

Is it possible to share the array in an efficient way? And if so, how?


回答1:


In current versions of .NET, any multi-megabyte array will end up on the large object heap and never move. However, to be safe, you should pin the array as fejesjoco said. Then the C++ code can save a pointer into the .NET array and update it in-place.




回答2:


Use memory mapped file. System.IO.MemoryMappedFiles in .NET and CreateFileMapping in C++.




回答3:


Does the .NET marshaler pass a copy, not a reference? 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.




回答4:


In vb.net, I've accomplished this by passing a reference to the first byte. 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.



来源:https://stackoverflow.com/questions/4521443/how-to-share-a-big-byte-array-between-c-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!