Search code examples
iosobjective-csyntaxcore-graphicsobjective-c-blocks

Use an ObjC Block as a callback for CGDataProviderCreateWithData


We want to call CGDataProviderCreateWithData() with the releaseData callback defined right in the arguments list. How can we do it?

I've tried a bunch of options, but was unable to crack the block syntax for this case.

The following:

const CGDataProviderRef provider = CGDataProviderCreateWithData(
    NULL,
    outputPixelDataBytes,
    pixelsSize,
    ^void(void * __nullable info, const void * data, size_t size) {
        free(data);
    });

doesn't compile with the error:

Passing 'void (^)(void * _Nullable, const void , size_t)' to parameter of incompatible type 'CGDataProviderReleaseDataCallback _Nullable' (aka 'void ()(void * _Nullable, const void * _Nonnull, unsigned long)')

Not sure what to change to get rid of the error.


Solution

  • CGDataProviderCreateWithData() does not take a block, it takes a function pointer, which is a different type of thing. You can't define a function inline like you're trying to do. You will have to define the function out-of-line and pass its address:

    static void MyReleaseCallback(void * __nullable info, const void *  data, size_t size)
    {
        free(data);
    }
    
    ...
    {
        ...
        const CGDataProviderRef provider = CGDataProviderCreateWithData(
            NULL,
            outputPixelDataBytes,
            pixelsSize,
            MyReleaseCallback);
        ...
    }