如何隐式投射

本文关键字:何隐式 | 更新日期: 2023-09-27 18:22:14

我正在尝试围绕一些本机DLL结构创建一些包装类。这是我得到的:

public class Event // <-- managed class
{
    internal SDL_Event _event;
    public EventType Type
    {
        get { return (EventType) _event.type; }
    }
    public KeyboardEvent Key
    {
        get
        {
            return new KeyboardEvent(_event.key); // <-- I want to avoid making a copy of the struct here
        }
    }
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct SDL_Event // <-- a union holding ~15 different event types
{
    [FieldOffset(0)] public UInt32 type;
    [FieldOffset(0)] public SDL_KeyboardEvent key;
    [FieldOffset(0)] private fixed byte _padding[56];
}
public class KeyboardEvent
{
    private SDL_KeyboardEvent _event;
    internal KeyboardEvent(SDL_KeyboardEvent e)
    {
        _event = e;
    }
    // some properties that deal specifically with SDL_KeyboardEvent 
}
[StructLayout(LayoutKind.Sequential)]
internal struct SDL_KeyboardEvent
{
    public UInt32 type; // <-- sits in the same memory location as SDL_Event.type
    public UInt32 timestamp;
    public UInt32 windowID;
    public byte state;
    public byte repeat;
    private byte _padding2;
    private byte _padding3;
    public SDL_Keysym keysym;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SDL_Keysym
{
    public UInt32 scancode;
    public Int32 sym;
    public UInt16 mod;
    private UInt32 _unused;
}

Event应该包裹SDL_EventKeyboardEvent应该包裹SDL_KeyboardEvent.我本质上想在访问Event.Key时将Event"投射"到KeyboardEvent,而无需复制任何数据。理想情况下,Event也可以直接投KeyboardEvent

如何隐式投射

unsafe static SDL_KeyboardEvent ToSDL_KeyboardEvent (SDL_Event event)
{
    return *((SDL_KeyboardEvent*) &event);
}

这是我能用结构做的最好的事情。 对于类,您必须以通常的方式编写一些显式转换,但这应该有助于这些转换。