我编写了一个简单的cpp函数,以从swift接收输入参数,并在cpp库的cpp函数中使用这些参数(如果有人熟悉CPLEX,我基本上是在swift中使用CPLEX cpp库。我想对问题进行预处理,然后将这些值传递给cpp进行优化)
我编写的简单cpp函数要求我提供一个double [][]
参数,该参数迅速转换为UnsafeMutablePointer< UnsafeMutablePointer<Double>? >
。我已经写了一小段代码,可以从[[Double]]
转换为该代码。
let arrayToConvert = [[3.0, 4.0], [2.0, 3.3]]
let outerArray = UnsafeMutablePointer< UnsafeMutablePointer<Double> >.allocate(capacity: arrayToConvert.count)
for idx in 0..<dists.count {
let arrPointer = UnsafeMutablePointer<Double>.allocate(capacity: dists[idx].count)
arrPointer.initialize(from: arrayToConvert[idx], count: arrayToConvert[idx].count)
outerArray.advanced(by: idx).pointee = arrPointer
}
然后,我使用创建的externalArray调用我的小型cpp函数opt(double **)
,但是它没有用,因为outerArray
与我的小型函数的要求不符,其中包含UnsafeMutablePointer< UnsafeMutablePointer<Double>? >
(请注意可选内容)。
所以我尝试改变
let outerArray = UnsafeMutablePointer< UnsafeMutablePointer<Double> >.allocate(capacity: arrayToConvert.count)
到
let outerArray = UnsafeMutablePointer< UnsafeMutablePointer<Double>? >.allocate(capacity: arrayToConvert.count)
这里的事情开始变得怪异。当添加可选的(?)时,出现错误“未定义符号:_opt”。有人可以指出我在这里想念的是什么或做错了什么吗?
以下是MWE代码:
main.swift
import Foundation
let arrayToConvert = [[3.0, 4.0], [2.0, 3.3]]
let outerArray = UnsafeMutablePointer< UnsafeMutablePointer<Double> >.allocate(capacity: arrayToConvert.count)
for idx in 0..<dists.count {
let arrPointer = UnsafeMutablePointer<Double>.allocate(capacity: dists[idx].count)
arrPointer.initialize(from: arrayToConvert[idx], count: arrayToConvert[idx].count)
outerArray.advanced(by: idx).pointee = arrPointer
}
opt(outerArray)
cp.cpp
#include "cp.hpp"
template <size_t rows, size_t cols>
double opt(double (&array)[rows][cols]) {
return 0.0;
}
cp.hpp
#ifndef cp_hpp
#define cp_hpp
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
double opt(double **);
#ifdef __cplusplus
}
#endif
#endif
paper1-Bridging-Header.h
#ifndef paper1_Bridging_Header_h
#define paper1_Bridging_Header_h
#include "paper1/cp/cp.hpp"
#endif