0

我想保留函数中分配的内存块(完整代码void ManipulateImagePixelData(CGImageRef inImage)请参见http://developer.apple.com/library/mac/#qa/qa1509/_index.html )

void ManipulateImagePixelData(CGImageRef inImage)
{
    // Create the bitmap context
    CGContextRef cgctx = CreateARGBBitmapContext(inImage);
    if (cgctx == NULL) 
    { 
        // error creating context
        return;
    }

     // Get image width, height. We'll use the entire image.
    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}}; 

    // Draw the image to the bitmap context. Once we draw, the memory 
    // allocated for the context for rendering will then contain the 
    // raw image data in the specified color space.
    CGContextDrawImage(cgctx, rect, inImage); 

    // Now we can get a pointer to the image data associated with the bitmap
    // context.
    void *data = CGBitmapContextGetData (cgctx);
    if (data != NULL)
    {

        // **** You have a pointer to the image data ****

        // **** Do stuff with the data here ****

    }

    // When finished, release the context
    CGContextRelease(cgctx); 
    // Free image data memory for the context
    if (data)
    {
        free(data);
    }

}

我已经修改了函数,以便我有宽度和高度,但我没有设法让内存块data指向。

我的功能如下:

void ManipulateImagePixelData(CGImageRef inImage, 
unsigned long * width, unsigned long * height, void * copy)

我不再在最后释放数据并承担以后释放它的责任。

我以为我可以做这样简单的事情:

(caller)
 void * rawPixels=NULL;
ManipulateImagePixelData([obj CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil],&imgWidth1, &imgHeight1, rawPixels)];


(ManipulateImagePixelData function)
void * pixels = CGBitmapContextGetData (cgctx);
    if (pixels != NULL) {
    *width=w;
    *height=h;
    copy=pixels;
    [...]

并让 rawPixels 指向上述块,但rawPixels在此调用后仍为 NULL。我对此有点困惑,我的 C 技能有点生疏。

我应该怎么做才能获取数据?

4

1 回答 1

2

您应该传递 ManipulateImagePixelData一个指向变量的指针,您希望在该变量中获取函数内分配的缓冲区的地址:

void ManipulateImagePixelData(CGImageRef inImage, unsigned long * width, unsigned long * height, void ** copy) {

        ...
        void* data = CGBitmapContextGetData (cgctx);
        *copy = data; // copy the output parameter
        ...
}  

并这样称呼它:

void * rawPixels=NULL;
ManipulateImagePixelData([obj CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil],&imgWidth1, &imgHeight1, &rawPixels)];

更好的是,您可以这样定义它:

void* ManipulateImagePixelData(CGImageRef inImage, unsigned long * width, unsigned long * height) {

          ...
          void* data = CGBitmapContextGetData (cgctx);
          ...
          return data;
}
于 2012-10-20T09:04:04.790 回答