Convert C # void * to byte []

In C #, I need to write T [] to a stream, ideally without any additional buffers. I have dynamic code that converts T [] (where T is a structure without objects) to void * and commits it to memory, and this works fine. When the stream was a file, I could use my own Windows API to pass void * directly, but now I need to write a generic Stream object that accepts byte [].

Question: Can anyone suggest a hacked way to create a dummy array object that does not actually have heap allocations, but points to an existing (and fixed) heap location?

This is the pseudo code I need:

void Write(Stream stream, T[] buffer)
{
    fixed( void* ptr = &buffer )    // done with dynamic code generation
    {
        int typeSize = sizeof(T);   // done as well

        byte[] dummy = (byte[]) ptr;   // <-- how do I create this fake array?

        stream.Write( dummy, 0, buffer.Length*typeSize );
    }
}  

Update: , fixed(void* ptr=&buffer) . [], , , .

? , [] . () T [], [] , T []. , T [] , [], [] .

@Microsoft Connect , , MS .

+3
4

. , T . , T - . . , T , , , .

, . , -, . JIT. , , , . , , , JIT.

, , . - .NET 4.0 MemoryMappedViewAccessor. , . System.Runtime.InteropServices.SafeBuffer, Reflector. , , CLR . , .

+3

stream.Write , , . , BinaryReader BinaryWriter , , , . , T .

unsafe static void Write<T>(Stream stream, T[] buffer) where T : struct
{
    System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned);
    IntPtr address = handle.AddrOfPinnedObject();
    int byteCount = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) * buffer.Length;
    byte* ptr = (byte*)address.ToPointer();
    byte* endPtr = ptr + byteCount;
    while (ptr != endPtr)
    {
        stream.WriteByte(*ptr++);
    }
    handle.Free();
}
0

: float [] []?

. CLR, .

, . , .

0

Check out this Inline MSIL article in C # / VB.NET and general pointers the best way to get your dream code :)

0
source

Source: https://habr.com/ru/post/1739661/


All Articles