如何使用Swift调用需要参数类型(int *)的Objective-C方法? [英] How can I use Swift to call an objective-C method that expects an argument of type (int *)?

查看:87
本文介绍了如何使用Swift调用需要参数类型(int *)的Objective-C方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现有的Objective-C方法具有以下签名:

An existing objective-C method has the following signature:

-(BOOL)barcodeSetScanBeep:(BOOL)enabled volume:(int)volume beepData:(int *)data length:(int)length error:(NSError **)error;

请注意,beepData:应该是(int *).

Note that beepData: expects (int *).

可以通过传入C数组在Objective-C中使用此方法:

This method can be used from objective-C by passing in a C array:

int beepData[] = {1200,100};

如何从Swift调用相同的方法?我最好的尝试let beepData: [Int] = [1200, 100]无法编译.

How can I call the same method from Swift? My best attempt, let beepData: [Int] = [1200, 100], doesn't compile.

推荐答案

int是一个32位C整数,并映射为Int32到Swift.

int is a C 32-bit integer and mapped to Swift as Int32.

一个int *参数映射为UnsafeMutablePointer<Int32>到Swift, 并且您可以通过&变量数组作为输入参数"传递.

A int * parameter is mapped to Swift as UnsafeMutablePointer<Int32>, and you can pass a variable array as "inout parameter" with &.

因此它应该大致如下:

var beepData : [ Int32 ] = [ 1200, 100 ]
var error : NSError?
if !DTDevices.sharedDevice().barcodeSetScanBeep(true, volume: Int32(100),
                beepData: &beepData, length: Int32(beepData.count),
                error: &error) {
    println(error!)
}

Swift还定义了类型别名

Swift defines also a type alias

/// The C 'int' type.
typealias CInt = Int32

,因此,如果您想强调一下,可以在上面的代码中用CInt替换Int32 您正在使用C整数.

so you could replace Int32 by CInt in above code if you want to emphasize that you are working with C integers.

有关更多信息,请参见与C API交互" "文档.

For more information, see "Interacting with C APIs" in the "Using Swift with Cocoa and Objective-C" documentation.

这篇关于如何使用Swift调用需要参数类型(int *)的Objective-C方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆