如何使用Swift调用期望类型为(int *)的参数的objective-C方法?

时间:2022-09-07 08:56:04

An existing objective-C method has the following signature:

现有的Objective-C方法具有以下特征:

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

Note that beepData: expects (int *).

请注意,beepData:expected(int *)。

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

通过传入C数组,可以从objective-C使用此方法:

int beepData[] = {1200,100};

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

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

1 个解决方案

#1


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

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

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

int *参数作为UnsafeMutablePointer 映射到Swift,您可以使用&将变量数组作为“inout参数”传递。

So it should roughly look like this:

所以它应该大致如下:

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 defines also a type alias

Swift还定义了一个类型别名

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

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

所以你可以在上面的代码中用CInt替换Int32,如果你想强调你正在使用C整数。

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

有关更多信息,请参阅“使用Swift with Cocoa和Objective-C”文档中的“与C API交互”。

#1


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

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

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

int *参数作为UnsafeMutablePointer 映射到Swift,您可以使用&将变量数组作为“inout参数”传递。

So it should roughly look like this:

所以它应该大致如下:

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 defines also a type alias

Swift还定义了一个类型别名

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

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

所以你可以在上面的代码中用CInt替换Int32,如果你想强调你正在使用C整数。

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

有关更多信息,请参阅“使用Swift with Cocoa和Objective-C”文档中的“与C API交互”。