gpt4 book ai didi

c++ - 将未知长度数组从 c 返回到结构体中的 Swift

转载 作者:行者123 更新时间:2023-11-30 17:26:41 25 4
gpt4 key购买 nike

我正在致力于 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 代码中做到这一点。我该怎么做?

最佳答案

你必须做:

Output* GetData( double InputA) {
Output* output = new 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;
}

不要忘记:

void DeleteOutput(Output* output)
{
if (output == nullptr) {
return;
}
delete [] output->DataArray;
delete output;
}

关于c++ - 将未知长度数组从 c 返回到结构体中的 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com