是否可以从 IntPtr 创建托管字节数组 +尺寸?
我正在使用一个公开回调函数的非托管 API。该函数接收一个IntPtr
和一个描述字节数组的整数。 API 希望我用数据填充它。
我想使用托管的 byte[] 来填充该缓冲区。到目前为止,我一直在这样做的方式是这样的:
public void MyCallback(IntPtr rawBufferPtr, int rawBufferLength)
{
var buffer = new byte[rawBufferLength];
<fill the buffer with whatever data I want>
Marshal.Copy(buffer, 0, rawBufferPtr, rawBufferLength);
}
是否可以避免 Marshal.Copy
并以某种方式分配 byte[]
来直接存储数据在rawBufferPtr
?
如果不是,还有哪些其他选项可以避免块复制? byte*
本质上是唯一的选择吗?
I am working with an unmanaged API which exposes a callback function. This function receives an IntPtr
and an integer which describe a byte array. The API expects me to fill it with data.
I would like to use a managed byte[]
to fill that buffer. The way I've been doing it so far is something like this:
public void MyCallback(IntPtr rawBufferPtr, int rawBufferLength)
{
var buffer = new byte[rawBufferLength];
<fill the buffer with whatever data I want>
Marshal.Copy(buffer, 0, rawBufferPtr, rawBufferLength);
}
Is it possible to avoid the Marshal.Copy
and somehow allocate the byte[]
to store the data directly at rawBufferPtr
?
If not, what other options are there for avoiding the block copy? Is byte*
essentially the only alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Marshal.WriteXXX 系列函数直接写入非托管缓冲区。
例子:
You can use the Marshal.WriteXXX family of functions to write directly to the unmanaged buffer.
Example:
如果您想避免调用
Marshal.Copy
,则byte *
本质上是唯一的选择。无法告诉运行时在特定的非托管地址分配字节数组。如果您想避免复制,则需要使用不安全代码。byte *
is essentially the only alternative, if you want to avoid the call toMarshal.Copy
. There's no way to tell the runtime to allocate a byte array at a particular unmanaged address. You'll need to use unsafe code if you want to avoid the copy.