如何在Swift中使用二维数组参数调用C函数?

时间:2015-04-07 03:27:06

标签: ios c arrays swift

在我的swift程序中,我已成功调用带有1-dim数组参数的C函数。但是当我尝试在Swift中调用带有2-dim数组参数的C函数时,它会提示如下错误:

'[([(Double)])]' is not convertible to 'UnsafeMutablePointer<(Double, Double, Double, Double, Double)>'

这是我在swift中的召唤:

var tSet  = [[Double]](count: 18, repeatedValue: [Double](count: 5,repeatedValue: Double(0.0)))
getTrainSet(sub_xlist, tSet)

和我的C函数定义:

void getTrainSet(const double *ax, double trainSet[18][5])

在Swift中初始化2-dim数组似乎有些不对劲。有人可以帮忙吗?谢谢。

2 个答案:

答案 0 :(得分:1)

此C函数在Swift中具有此类型

void getTrainSet(const double *ax, double trainSet[2][2]) // C
getTrainSet(ax: UnsafePointer<Double>, 
            trainSet: UnsafeMutablePointer<(Double, Double)>)  //Swift

要将var转换为UnsafePointer,您必须在将&传递给函数时使用var sub_xlist = 10.0 getTrainSet(&sub_xlist)

double a[2][2] // In C
[(Double, Double)]() // In Swift

Int a[18][3] // In C
[(Int, Int, Int)]() // In Swift

二维数组在Swift中转换为元组数组。第二维确定了元组中有多少元素 示例

UnsafeMutablePointer<(Double, Double)>

(Double, Double) - 是一个类型为trainSet的元组数组 在您的示例中,var sub_xlist = 10.0 var p: UnsafeMutablePointer<(Double, Double, Double, Double, Double)> = nil var tuples = [(Double, Double, Double, Double, Double)]() getTrainSet(&sub_xlist, &tuples) getTrainSet(&sub_xlist, p) 是一个包含5个双元素的元组数组

解决方案

{{1}}

在此处阅读更多Interacting with C APIs

答案 1 :(得分:1)

void getTrainSet(const double *ax, double trainSet[18][5])

被翻译成Swift:

func getTrainSet(ax: UnsafePointer<Double>, trainSet: UnsafeMutablePointer<(Double, Double, Double, Double, Double)>)

解决方法1

制作Array (Double, Double, Double, Double, Double)

var sub_xlist: Double = 0
var tSet = [(Double,Double,Double,Double,Double)](count: 18, repeatedValue: (0,0,0,0,0))
getTrainSet(&sub_xlist, &tSet)

得到如下结果:

tSet[1].3 // equivalent to `tSet[1][3]` in C

溶液2

在C中,double trainSet[18][5]只是9018 * 5double s的缓冲区。您可以使用[Double]元素制作90,并将其作为UnsafeMutablePointer传递:

var sub_xlist: Double = 0
var tSet = [Double](count: 18 * 5, repeatedValue: 0)
getTrainSet(&sub_xlist, UnsafeMutablePointer(tSet))

你可以得到如下结果:

let row = 1
let col = 3
tSet[row * 5 + col] // equivalent to `tSet[row][col]` in C