Swift中的"向下倾斜"C结构

Gen*_*isa 8 ios swift

Core MIDI是一种C API,提供其他地方没有的功能.

当用户的MIDI设置发生变化时(例如,您插入设备),会有通知.

这是被调用的函数的类型.

typealias MIDINotifyProc = CFunctionPointer<((UnsafePointer<MIDINotification>, UnsafeMutablePointer<Void>) -> Void)>
Run Code Online (Sandbox Code Playgroud)

第一个参数是MIDINotification结构,如下所示:

struct MIDINotification {
    var messageID: MIDINotificationMessageID
    var messageSize: UInt32
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样实现回调:

func MyMIDINotifyProc (np:UnsafePointer<MIDINotification>, refCon:UnsafeMutablePointer<Void>) {        
    var notification = np.memory       
    switch (notification.messageID) {

    case MIDINotificationMessageID(kMIDIMsgObjectAdded):
        // In Objective-C you would just do a cast here
        // This is the problem line
        var m = np.memory as MIDIObjectAddRemoveNotification
Run Code Online (Sandbox Code Playgroud)

您将查看messageID成员以查看您刚刚收到的通知类型.有几个(我只展示一个).对于每种通知,您将获得传入的不同结构.这是添加或删除设备时获得的结构:

struct MIDIObjectAddRemoveNotification { 
    var messageID: MIDINotificationMessageID
    var messageSize: UInt32
    var parent: MIDIObjectRef
    var parentType: MIDIObjectType
    var child: MIDIObjectRef
    var childType: MIDIObjectType
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此结构具有其他信息.例如,"child"可能是设备的端点,因此您需要这些字段.

问题是从MIDINotification结构(回调签名所需)转换为MIDIObjectAddRemoveNotification.我使用"as"显示的行不起作用.

你对这种"向下倾倒"有什么建议吗?

Vat*_*not 2

我建议您研究一下标准库函数unsafeBitCast