简体   繁体   中英

How can you convert void* to a specific type in c#?

I have a series of classes, each built for a specific type ( Byte , UInt16 , Double , etc; each is defined by a TypeCode ). Each class has nearly the same code, but does some casts to its specific type. Note: there is a class member defined as: void* _baseAddress; and ClassX* _table;

A simplified example method:

    public unsafe UInt16 GetValue(int x)
    {
        return *((UInt16*) _baseAddress + (_table+ x)->entry);
    }

I want, assuming I have a class member called MyType which is defined by typeof(inputType) , to do this:

    public unsafe object GetValue(int x)
    {
        return *((MyType*) _baseAddress + (_table+ x)->entry);
    }

This clearly doesn't work. I've been trying to read up on use of Func and delegates but keeping hitting a wall that a void* can't be converted like I want.

Because I think it adds context. This is trying to get the value at a given location. I have a mirror method that should have:

*((MyType*) _baseAddress + (_table + x)->XEntry ) = inputValue;

Note: performance is important. I cannot allocate new memory, nor can I burn a bunch of processor time on the conversions

If I understand your problem correctly, this will accomplish what you want:

    /// <summary>
    /// Maps the supplied byte array onto a structure of the specified type.
    /// </summary>
    public static T ToStructure<T>(byte[] data)
    {
        unsafe
        {
            fixed (byte* p = &data[0])
            {
                return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
            }
        };
    }

Which demonstrates the principle. You should be able to adapt it to your specific purposes.

This function does the reverse operation:

    /// <summary>
    /// Converts the supplied object to a byte array.
    /// </summary>
    public static byte[] ToByteArray(object obj)
    {
        int len = Marshal.SizeOf(obj);
        byte[] arr = new byte[len];
        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(obj, ptr, true);
        Marshal.Copy(ptr, arr, 0, len);
        Marshal.FreeHGlobal(ptr);
        return arr;
    }

Marshal is in System.Runtime.InteropServices .

If you need the absolute fastest possible speed, have a look here .

You should also look at the BitConverter class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM