I created a C array like this:
unsigned char colorComps[] = {2, 3, 22, 55, 9, 1};
which I want to pass to an initializer of an Objective-C object.
So I think I have to put the array on the heap:
size_t arrayByteSize = numColorCompVals * sizeof(unsigned char);
unsigned char *colorCompsHeap = (unsigned char*)malloc(arrayByteSize);
Then I have to write my first "stack memory array" to the heap array in for loop:
for (int i = 0; i < numColorCompVals; i++) {
colorCompsHeap[i] = colorComps[i];
}
Side question: Is there a more elegant solution to avoid the for-loop step?
And then I pass it to the method:
defined as
- (id)initWithColorCompsC:(unsigned char *)colorCompsHeap;
TheObject *obj = [[TheObject alloc] initWithColorCompsC:colorCompsHeap];
TheObject
has a property to hold the C-array:
@property (nonatomic, assign) unsigned char *colorComps;
And in -dealloc I free it:
free(_colorComps);
This is in theory. I use ARC for Objective-C. Am I doing this correct or is there a better way?
This seems fine, however...
malloc()
;memcpy()
. Instead of your for loop, writememcpy(dest, src, size)
.If
TheObject
is going to free the array, then itsinit
method should be the one to make the copy, NOT the caller. That way each instance ofTheObject
make its own copy and frees its own copy, it owns that copy.Also, then it doesn't matter where the parameter to the init comes from, stack or heap. It won't matter if the
init
method makes a copy of it.Use memcpy to make the copy, with
sizeof
the destination array, like this for the .m file:Doesn't seems correct to me, you are filling
colorCompsHeap
(an array of unsigned chars) with the values ofcolorComps[]
(an array of doubles)Outputs
0.000000