简体   繁体   English

将字节数组从c ++传递到ac#汇编有哪些不同的方法?

[英]What are the different ways to pass a byte array from c++ to a c# assembly?

I would like to know the different approaches that can be used to pass a byte array from c++ to c# and their performance characteristics. 我想知道可用于将字节数组从c ++传递到c#的不同方法及其性能特征。 I would ideally like to pass a pointer to a byte array in an unmanaged heap to the C# assembly and avoid any copy operation. 理想情况下,我希望将非托管堆中的字节数组的指针传递给C#程序集,并避免任何复制操作。

Assuming that you're calling a C# method from unmanaged C++ using something like Reverse P/Invoke , you can just pass the pointer. 假设您正在使用反向P / Invoke之类的方法从非托管C ++调用C#方法,则只需传递指针即可。 The C# code should accept the pointer as IntPtr or UIntPtr , which it can then treat as an unmanaged array. C#代码应将指针接受为IntPtrUIntPtr ,然后可以将其视为非托管数组。

There are a number of ways to access the data behind that pointer once you pass it to the C# code. 将指针传递给C#代码后,有多种方法可以访问该指针后面的数据。 You can use Unsafe Code and Pointers , which is probably the highest performance if you're partying on individual bytes. 您可以使用Unsafe Code and Pointers ,如果您要处理单个字节,则可能是最高的性能。

If you want to treat it as a stream of bytes, you could use UnmanagedMemoryStream . 如果要将其视为字节流,则可以使用UnmanagedMemoryStream

Or, you can use the Marshal.Copy and Marshal.Read (many variants) methods to read different data types at different areas within that buffer. 或者,您可以使用Marshal.CopyMarshal.Read (许多变体)方法来读取该缓冲区内不同区域的不同数据类型。

None of the above require any copying of data other than the pointer itself between the C++ and C# code. 除了C ++和C#代码之间的指针本身以外,上述内容均不需要任何数据复制。

There are undoubtedly other ways to access the memory from C# that I haven't listed above. 毫无疑问,我上面没有列出其他从C#访问内存的方法。 The gist of it is that passing an array of bytes either way is pretty painless. 其要点是,以任何一种方式传递字节数组都非常容易。

I think you can have pointers on C++ side and ref on the C# side. 我认为您可以在C ++方面具有指针,而在C#方面具有ref。 Refer the link provided in the comment. 请参阅注释中提供的链接。

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

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