0
我正在C++類和Swift之間進行橋接。我知道我只能與c和Objective C接口,所以我在c中編寫了一個包裝函數。返回未知長度數組從c到Swift結構
我需要返回一些數據,我已經打包在一個結構中,並且結構中包含一個未知長度的數組。所有這些都需要用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.
}
從斯威夫特我可以調用
var swoutput = GetData(1.0)
var count = swoutput.memory.DataArrayLength
我的問題是:
有沒有更好的方法做到這一點?怎麼樣?
我應該如何分配,傳遞,返回輸出結構?我意識到目前的方法的問題,但不知道最好的解決方案。
我仍然需要從DataArray釋放內存。我想我需要從Swift代碼中做到這一點。我該怎麼做呢?
'結構輸出輸出;'在結構輸出*的GetData(雙InputA)的'範圍定義'功能。一旦函數調用返回,'output'將不存在。所以返回'&output'是錯誤的。您可以嘗試使用指針。 – 2014-11-01 14:43:43