将Objective-C代码转换为Swift时的EXC_BAD_ACCESS

时间:2016-01-20 07:42:52

标签: ios objective-c swift

我尝试在项目中使用Objective-C框架,并在将Objective-C代码转换为Swift时遇到一些问题。

其中一个API:

- (void)ioFrameChannel:(PTChannel*)channel didReceiveFrameOfType:(uint32_t)type tag:(uint32_t)tag payload:(PTData*)payload

payload.data 是这样的结构:

typedef struct _PTExampleTextFrame {
  uint32_t length;
  uint8_t utftext[0];
} PTExampleTextFrame;

我想得到PTExampleTextFrame.utftext这是从框架发送的消息

所以,我创建了一个本地struct

struct CPTExampleTextFrame {
    var length: UInt32
    var utf8text: UnsafePointer<UInt8>
}

写得像这样:

var textFrame = UnsafePointer<CPTExampleTextFrame>(payload.data).memory
textFrame.length = CFSwapInt32(textFrame.length)
print(textFrame.length) // textFrame.length is correct!
let message = NSString(bytes: textFrame.utf8text, length: Int(textFrame.length), encoding: NSUTF8StringEncoding) // error
print(message)
  

但是我收到一个错误:EXC_BAD_ACCESS(code = 1,address = 0x31)

谁能告诉我这是什么问题?

我还提供了Objective-C中的框架示例:

- (void)ioFrameChannel:(PTChannel*)channel didReceiveFrameOfType:(uint32_t)type tag:(uint32_t)tag payload:(PTData*)payload {
  if (type == PTExampleFrameTypeTextMessage) {
    PTExampleTextFrame *textFrame = (PTExampleTextFrame*)payload.data;
    textFrame->length = ntohl(textFrame->length);
    NSString *message = [[NSString alloc] initWithBytes:textFrame->utf8text length:textFrame->length encoding:NSUTF8StringEncoding];
    [self appendOutputMessage:[NSString stringWithFormat:@"[%@]: %@", channel.userInfo, message]];
  } else if (type == PTExampleFrameTypePing && peerChannel_) {
    [peerChannel_ sendFrameOfType:PTExampleFrameTypePong tag:tag withPayload:nil callback:nil];
  }
}

2 个答案:

答案 0 :(得分:1)

由于Objective-C是C的超集,我真的建议您将与C接口的代码保留为Objective-C代码。直接连接C和Swift是一种绝对的痛苦。

一个char数组和一个指向char的不安全可变指针显然不兼容。

答案 1 :(得分:0)

您不需要创建本地结构,它的内存布局与c类型不兼容。

澄清之后:

let x: PTExampleTextFrame = UnsafeMutablePointer<PTExampleTextFrame>(payload.data).memory

然后使用x