我的Swift如何写入C结构体的Swift示例,然后将示例传递给C函数?“写”崩溃

w8biq8rn  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(94)

我需要在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  )
kcwpcxri

kcwpcxri1#

在写入时,您没有为data分配任何内存,因此当您写入NULL指针时,应该会出现这种情况。您可能有其他代码没有显示,我将在下面讨论。
如果我理解你的代码,就像你展示的那样,它是这样的:

// create a stack instance, with all 0/NULL values
var sleep_time_all = emxArray_real_T()  

// Your comment says "to empty," but this line doesn't free any memory; it just
// makes a new stack instance, and forgets (leaking if it had allocated memory)
// the previous one.
sleep_time_all = emxArray_real_T()

// Your comment says "to reset array usage," but this just sets the value to 0.
// It doesn't modify `data` in any way if you're expecting it to do that.
sleep_time_all.allocatedSize = 0

// Assuming this really is the next line as shown, since `allocatedSize` is 0, 
// this resolves to index 0, but since `data` is NULL, writing to `data[0]` is a crash
sleep_time_all.data[ Int( sleep_time_all.allocatedSize) * 8 ] = some_Double_number

有可能您在为data分配内存的过程沿着,没有在这里显示它。如果是这样的话,那么错误很可能是* 8,我猜这可能是基于“8字节的Double?“如果是这样的话,这是双重倍增。data[n]已经将n乘以Element的大小以获得偏移量。但是这仍然会超过数组的末尾,因为allocatedSize比最后一个索引大1。我想你的意思是:

// Write to the last element, assuming `allocatedSize` is the total number of Doubles
sleep_time_all.data[Int(sleep_time_all.allocatedSize) - 1] = some_Double_number

相关问题