我需要在Swift中示例化一个C结构体,向它写入数据,最后将其传递给一个C函数。
构建正常,但“写入”崩溃....
C struct(from .h)...
struct emxArray_real_T { // sleep stage timestamp record ie. sleep_time_all.data
double *data;
int *size;
int allocatedSize;
int numDimensions;
boolean_T canFreeData;
};
Swift上面的C结构示例...
var sleep_time_all = emxArray_real_T()
相同示例的Swift init...
sleep_time_all = emxArray_real_T() // to empty prior use of array sleep_time_all.data
sleep_time_all.allocatedSize = 0 // to reset array usage
Swift write to array gets***RUN-TIME ERROR***...
sleep_time_all.data[ Int( sleep_time_all.allocatedSize) * 8 ] = some_Double_number
//<<<<<<<<<<<< crash error:
// "Thread 1: Swift runtime failure: Unexpectedly found nil while implicitly unwrapping an Optional value"
C函数
void compute_sleep_stats_new(const emxArray_real_T *sleep_time_all )
{...}
// Pass instantiation into C function...
compute_sleep_stats_new( &sleep_time_all )
1条答案
按热度按时间kcwpcxri1#
在写入时,您没有为
data
分配任何内存,因此当您写入NULL指针时,应该会出现这种情况。您可能有其他代码没有显示,我将在下面讨论。如果我理解你的代码,就像你展示的那样,它是这样的:
有可能您在为
data
分配内存的过程沿着,没有在这里显示它。如果是这样的话,那么错误很可能是* 8
,我猜这可能是基于“8字节的Double?“如果是这样的话,这是双重倍增。data[n]
已经将n
乘以Element的大小以获得偏移量。但是这仍然会超过数组的末尾,因为allocatedSize
比最后一个索引大1。我想你的意思是: