我正在使用C库,并且想使用Pointers
作为参数来调用函数。它说我需要将Double
转换为UnsafeMutablePointer<Double>
。
这就是我走了多远:
class ViewController: UIViewController {
var buffer1 = [Double]()
var buffersize = [Int32]()
var ar = UnsafeMutablePointer<Double>.allocate(capacity: 10)
var ar2 = UnsafeMutablePointer<Double>.allocate(capacity: 2)
override func viewDidLoad() {
super.viewDidLoad()
randomBuffer()
print(buffer1)
ar.deallocate()
ar2.deallocate()
let grade = ar.pointee
let isevent = ar2.pointee
print(grade, isevent)
let pointer = app_ios_ersatzfunktion(buffer1, buffersize, ar, ar2)
print(pointer)
}
func randomBuffer()
{
let randomDouble = Double.random(in: -1...2)
if buffer1.count<200{
buffer1.append(randomDouble)
}
else {
buffer1.removeFirst()
buffer1.append(randomDouble)
}
}
}
我的C代码是使用Matlab创建的,如下所示:
void app_ios_ersatzfunktion(const double buffer2_data[], const int buffer2_size
[2], double *grade, double *event_found)
{
double jerk;
*grade = 0.0;
*event_found = 0.0;
jerk = (buffer2_data[buffer2_size[1] - 1] - buffer2_data[buffer2_size[1] - 2])
/ 0.01;
if ((jerk >= 200.0) || (jerk <= -200.0)) {
*event_found = 1.0;
*grade = jerk / 50.0;
}
}
答案 0 :(得分:1)
您可以将Swift数组直接传递给C函数,这将传递元素存储的地址。对于“输出参数”,您必须使用&
将变量作为“输入参数”传递:
let buffer2_data: [Double] = ...
let buffer2_size: [CInt] = ...
var grade: Double = 0
var event_found: Double = 0
app_ios_ersatzfunktion(buffer2_data, buffer2_size, &grade, &event_found)
print(grade, event_found)