Am I correctly creating and passing this C array to Objective-C method and referencing it with a property?

你离开我真会死。 提交于 2019-12-02 10:20:57

If TheObject is going to free the array, then its init method should be the one to make the copy, NOT the caller. That way each instance of TheObject 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:

@interface PTTEST ()
@property (nonatomic, assign) unsigned char *colorComps;
@end

@implementation PTTEST

- (void)dealloc
{
    free(_colorComps);
}

- (id)initWithColorCompsC:(unsigned char *)colorComps
       numberOfColorComps:(unsigned)numberOfColorComps
{
    self = [super init];
    if (self) {
        // compute size based on sizeof the first element (in case
        // the element type get changed later, this still works right)
        size_t arraySize = sizeof(colorComps[0]) * numberOfColorComps;

        _colorComps = malloc(arraySize);

        memcpy(_colorComps, colorComps, arraySize);
    }
    return self;
}

@end

This seems fine, however...

  1. Don't cast the return value of malloc();
  2. and don't reinvent memcpy(). Instead of your for loop, write memcpy(dest, src, size).

Doesn't seems correct to me, you are filling colorCompsHeap(an array of unsigned chars) with the values of colorComps[] (an array of doubles)

unsigned char u = 0.2;

printf("%f\n", (double)u);

Outputs 0.000000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!