NSValue:getValue: strange behavior,why this happens?

后端 未结 2 711
情深已故
情深已故 2021-01-14 18:25

I try to pass CGRect to NSInvocation (setArgument:atIndex:). I wrap it by NSValue, push to the NSArry,then get from NSArray and use NSValue (getValue:). Calling of (getValue

相关标签:
2条回答
  • 2021-01-14 18:51

    You can't fit an NSRect into a void*. The correct code would be:

    NSRect buffer;
    [currentVal getValue:&buffer];
    

    Or alternatively, if you don't know the contents of the NSValue object:

    NSUInteger bufferSize = 0;
    NSGetSizeAndAlignment([currentVal objCType], &bufferSize, NULL);
    void* buffer = malloc(bufferSize);
    [currentVal getValue:buffer]; //notice the lack of '&'
    //do something here
    free(buffer);
    

    The value for i is changing because your code causes an overflow into other stack-allocated variables.

    0 讨论(0)
  • 2021-01-14 19:04

    In:

     void *bufferForValue;
     [currentVal getValue:&bufferForValue];
    

    you are copying currentVal value to a buffer which has the size of void* (a pointer); now, see getValue reference:

    getValue:

    Copies the receiver’s value into a given buffer.

    buffer

    A buffer into which to copy the receiver's value. buffer must be large enough to hold the value.

    Since the value you copying over to the buffer cannot fit in a void*, you are thus overwriting your stack, since you are writing to the address of a local variable; this has likely the effect of overwriting the i local variable, so that explains what is happening.

    0 讨论(0)
提交回复
热议问题