【发布时间】:2014-11-01 14:39:12
【问题描述】:
我正在研究 C++ 类和 Swift 之间的桥梁。我知道我只能与 c 和 Objective C 交互,所以我正在用 c 编写一个包装函数。
我需要返回一些我已经打包在一个结构中的数据,并且该结构包含一个未知长度的数组。所有这些都需要通过 c 来与 Swift 交互。
我的结构如下:
struct Output {
double DataA;
long DataArrayLength;
double *DataArray;
};
我在c中编写了以下函数来打包数据:
struct Output* GetData( double InputA) {
struct Output output;
output.DataArrayLength = 100; // The length will only be known at run time and
// once I get into this function.
output.DataArray = new double[output.DataArrayLength];
///
Fill in the data array - some complicated calculations behind this.
output.DataArray[0] = 12345.0;
output.DataArray[99] = 98761.0;
///
return &output; // Getting warning Address of stack associated with local variable 'output' returned.
}
然后我可以从 Swift 调用
var swoutput = GetData( 1.0)
var count = swoutput.memory.DataArrayLength
我的问题是:
有没有更好的方法来做到这一点?怎么样?
我应该如何分配、传递、返回输出结构?我意识到当前方法存在问题,但不确定最佳解决方案。
我仍然需要从 DataArray 中释放内存。我想我需要从 Swift 代码中做到这一点。我该怎么做?
【问题讨论】:
-
struct Output output;定义在struct Output* GetData( double InputA)函数的范围内。一旦函数调用返回,output将不存在。所以返回&output是错误的。您可以尝试改用指针。