EXC_BAD_ACCESS when modifying data returned by CFDataGetBytePtr

330 Views Asked by At

Making long story short, I want to capture a window and then modify the bytes buffer:

struct CaptureObject
    {
        unsigned char* bgraData;
        CFDataRef bgraDataRef;
        CGDataProviderRef provider;
        int width;
        int height;
        int bytesPerRow;
    };

CaptureObject obj;

CGImageRef windowImage = CGWindowListCreateImage(captureCGRect, kCGWindowListOptionIncludingWindow, windowId, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque);

obj.width = CGImageGetWidth(windowImage);
obj.height = CGImageGetHeight(windowImage);
obj.bytesPerRow = CGImageGetBytesPerRow(windowImage);

obj.provider = CGImageGetDataProvider(windowImage);
obj.bgraDataRef = CGDataProviderCopyData(obj.provider);
obj.bgraData = const_cast<unsigned char*>(CFDataGetBytePtr(obj.bgraDataRef));

//Read and right obj.bgraData;

CGImageRelease(windowImage);
CFRelease(browserImage.bgraDataRef);
CGDataProviderRelease(browserImage.provider);

I can read the data but getting a crash when trying to write to this buffer. As clearly noticed in the documentation 'CFDataGetBytePtr':

Returns a read-only pointer to the bytes of a CFData object.

But what does it actually means? If this is only a compilation syntax, I thought that 'const_cast' should solve this. So My question is how the OS mange to allocate the object in "read only" segment (something like "code segment");

P.S. I'm trying to avoid using 'CFDataGetByte' that actually copies the data because it is too expensive for my purpose.

0

There are 0 best solutions below