C# - 如何将 IntPtr 缓冲区数据保存到文件(最快的方式)? [英] C# - How to Save IntPtr Buffer Data to File (quickest way)?

查看:20
本文介绍了C# - 如何将 IntPtr 缓冲区数据保存到文件(最快的方式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码将字节从非托管代码中的 IntPtr 缓冲区保存到文件.这是一个简单的回调函数:

I'm using this code to save bytes from a IntPtr buffer in unmanaged code to file. It's a simple callback function:

private void callback(IntPtr buffer, int length)
{
    byte[] bytes = new byte[length];
    Marshal.Copy(buffer, bytes, 0, length);
    FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write);
    file.Write(bytes, 0, length);
    file.Close();
}

我想要的是将这些数据存储到文件中并将其丢弃.据我了解,非托管代码中有一个缓冲区,而我的代码中有第二个缓冲区.不想复制我想要的周围的数据直接:

What I want is to store this data to file and throw it away. From what I understand there is a buffer in the unmanaged code and a 2nd one in MY code. I don't want to copy the data around I want it directly:

// bad:     (unmanaged) buffer -> (managed) bytes -> file
// awesome: (unmanaged) buffer ->                    file

对于我的任务,我需要以最快的方式将数据存储到文件中.

For my task I need the most quickest way to store the data to file.

推荐答案

嗯,出于某种原因,它被称为托管" :-)你可以做的是声明 WriteFile 使用 P/Invoke,像这样:

Well, it's called "managed" for some reason :-) What you can do though is declare WriteFile using P/Invoke, like this:

private void callback(IntPtr buffer, int length)
{
    FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write);
    int written;
    WriteFile(file.Handle, buffer, length, out written, IntPtr.Zero);
    file.Close();
}

 [DllImport("kernel32.dll")]
 private static extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, int NumberOfBytesToWrite, out int lpNumberOfBytesWritten, IntPtr lpOverlapped);

这篇关于C# - 如何将 IntPtr 缓冲区数据保存到文件(最快的方式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆