本文介绍了可我如何在C#中stream.Read到非托管内存流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用UnmanagedMemoryStream读取C#非托管的内存,但我该怎么做反向?

I can read unmanaged memory in C# using UnmanagedMemoryStream, but how can I do the reverse?

我想从托管流直接读入非托管内存,而不是第一次读入一个byte [],然后复制。我正在做异步流读取的大量请求,因此增加的内存是显著(更不用提其他副本)。

I want to read from a managed stream directly into unmanaged memory, instead of first reading into a byte[] and then copying. I'm doing async stream reading on a large number of requests, so the added memory is significant (not to mention the additional copy).

推荐答案

我觉得这是不是真的有可能。当你谈论一个管理流,我想你指的的System.IO.Stream的实例或其中一个子类。

I think that it is not really possible. When you talk about a managed stream, I suppose you are refering to an instance of System.IO.Stream or a subclass hereof.

这个类以字节[成员]作为参数,这是一个托管类。

The members of this class take byte[] as a parameter, and that is a managed class.

我猜你能来是创建一个托管的byte [],然后在一个不安全块创建一个字节*,然后通过字节*到最近的任何需要一个非托管的引用:

I guess that the closest you can come is creating a managed byte[], and then creating a byte* in an unsafe block, and then passing the byte* to whatever needs an unmanaged reference:

unsafe function test()
{
    var buffer = new byte[1024];
    fixed (byte* bufferPtr = &buffer[0])
    {
        // Read bytes and pass the ptr to a function that needs to
        // operate on data directly
    }
}

但是,这不是你问什么了

But that is not exactly what you're asking for

修改:要小心。你提到一些有关异步读取。只要你是固定的边界之外,气相色谱可以在内存中移动的阵列。如果你已经通过指针,继续在不同的线程操作的一些不安全功能,指针会指向一个无效的内存位置。

edit: Be careful though. You mention something about async reads. As soon as you're outside the fixed boundary, the GC may move the array around in memory. And if you've passed the pointer to some "unsafe" function that continues to operate in a different thread, the pointer will point to an invalid memory location.

这篇关于可我如何在C#中stream.Read到非托管内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 09:24
查看更多