加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C和Objective-C – 正确释放无符号字符指针的方法

发布时间:2020-12-16 03:20:17 所属栏目:百科 来源:网络整理
导读:在我的应用程序中,我使用此函数创建一个unsigned char指针: - (unsigned char*)getRawData{// First get the image into your data bufferCGImageRef image = [self CGImage];NSUInteger width = CGImageGetWidth(image);NSUInteger height = CGImageGetHei
在我的应用程序中,我使用此函数创建一个unsigned char指针:
- (unsigned char*)getRawData
{
// First get the image into your data buffer
CGImageRef image = [self CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData,width,height,bitsPerComponent,bytesPerRow,colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextSetBlendMode(context,kCGBlendModeCopy);

CGContextDrawImage(context,CGRectMake(0.0f,0.0f,(CGFloat)width,(CGFloat)height),image);
CGContextRelease(context);

// Now your rawData contains the image data in the RGBA8888 pixel format.

return rawData;
}

在另一个类中,我将一个属性分配给该指针,如下所示:self.bitmapData = [image getRawData];

在这个过程中我可以释放那个malloc内存吗?当我尝试在dealloc中释放属性时,它会给我一个exc_bad_access错误.我觉得我在这里缺少一个基本的c或objective-c概念.所有帮助表示赞赏.

解决方法

关于在objective-c here中使用malloc / free的安全性有一个很好的讨论.

只要你正确地释放()你malloc()的内存,应该没有问题.

我个人认为使用NSMutableData或NSMutableArray更容易.如果您不需要最终性能,我不会直接使用C malloc / free语句.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读