调用一个接受带有非托管IntPtr的byte []的C#方法

时间:2013-12-18 14:51:28

标签: c# interop c++-cli marshalling

我的程序由3个组成部分组成 1)C#前端
2)C ++ / CLI包装器
3)C ++后端

C#FE包含一种通过从Stream类获取HttpWebRequest来与网络通信的方法。此方法通过包装器传递给C ++后端,后端在有新字节要发送时调用它。

C#  
void WriteBytes(IntPtr pBody, int cbBody); // Marshal.Copy'es the data from
     IntPtr to managed byte[], then calls Stream.WriteBytes(byte[], ...)

C++/CLI
void WriteBytes(System::IntPtr pBody, int cbBody); // uses
     Marshal::GetFunctionPointerForDelegate

C++
void WriteBytes(const BYTE* pBody, size_t cbBody); // calls function pointer 
    received from the wrapper

我想优化它以不将字节从非托管BYTE *复制到托管字节[],因为我控制所有阶段的内存分配。
这可能吗?
它应该提高性能吗?

1 个答案:

答案 0 :(得分:0)

您无法将任意缓冲区转换为array<Byte>,但您可以固定array<Byte>并获取指向其第一个元素的非托管指针,直到取消固定该对象为止。

如果您想要使用C#,请参阅pin_ptr<>课程C++/CLIGCHandle课程。