实现一个将C数组的基元数包装成CFNumbers的CFArray的方法的最佳方法是什么?
我想打电话给如下的人:
double values[] = {1.2345, 678.9};
CFArrayRef arr = NumberWrappedValuesArray(&values, 2, kCFNumberDoubleType);
试过这个:
CFArrayRef NumberWrappedValuesArray(void * valueArrayPtr, CFIndex count, CFNumberType numberType) {
CFMutableArrayRef array = CFArrayCreateMutable(NULL, count, &kCFTypeArrayCallBacks);
for (int i = 0; i < count; i++) {
CFNumberRef numberWrappedValue = CFNumberCreate(NULL, numberType, &valueArrayPtr[i]);
CFArrayAppendValue(array, numberWrappedValue);
CFRelease(numberWrappedValue);
}
CFRelease(array);
return array;
}
它不起作用(返回的数组有0个元素),为什么以及如何修复它?
有没有更优雅的方法,可能避免可变CFArray?
谢谢!
最佳答案
您可以使用CFArrayCreate
。
例子:
CFArrayRef NumberWrappedValuesArray(void *valueArrayPtr, size_t size, CFIndex count, CFNumberType numberType) {
size_t i, n;
CFArrayRef ret;
CFNumberRef *ref = malloc(sizeof(CFNumberRef) * count);
/* create array of boxed types. */
for (i = 0, n = count; i < n; ++i)
ref[i] = CFNumberCreate(NULL, numberType, ((char *)valueArrayPtr) + (size * i));
/* create CFArray. */
ret = CFArrayCreate(NULL, (const void **)ref, count, &kCFTypeArrayCallBacks);
/* release boxed types and malloc'ed array. */
for (i = 0; i < n; ++i)
CFRelease(ref[i]);
free(ref);
/* return CFArray, without releasing first! Has to be done by the caller. */
return ret;
}
为了清楚起见,省略了错误处理。
关于c - 将C原语值包装在CFNumbers的CFArray中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41782290/