可可&可可触摸。如何从普通 ole 指针创建 NSData 对象?

发布于 2024-09-05 12:24:28 字数 289 浏览 3 评论 0原文

我在 NSOperation 实例中分配了一大堆数据。我有一个指针:

data = malloc(humungous_amounts_of_god_knows_what);
uint8_t* data;

如何将其打包为 NSData 实例并将其返回到主线程?我假设转换为 NSData 实例后我可以简单地调用:

free(data);

是吗?

另外,回到主线程如何检索指针?

谢谢,
道格

I have malloc'd a whole mess of data in an NSOperation instance. I have a pointer:

data = malloc(humungous_amounts_of_god_knows_what);
uint8_t* data;

How do I package this up as an NSData instance and return it to the main thread? I am assuming that after conversion to an NSData instance I can simply call:

free(data);

Yes?

Also, back on the main thread how do I retrieve the pointer?

Thanks,
Doug

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若言繁花未落 2024-09-12 12:24:29

您需要 -dataWithBytes:length: 或其变体之一:

NSData *d = [NSData dataWithBytes:data length:lengthOfDataInBytes];

复制字节,然后您可以free(data)。要保存副本,假设使用 malloc 分配 data 使用:

NSData *d = [NSData dataWithBytesNoCopy:data length:lengthOfDataInBytes];

您不应该在以下位置的缓冲区上调用 free在这种情况下,因为 NSData 实例将为您释放它。

请注意,所有这些方法都会返回一个 autoreleased 实例,因此如果您想在线程之间保留它(并且不使用 GC),您可能必须保留它。您可以使用等效的 alloc/initWithBytes:... 初始化器来代替。

要获取指向 NSData 内容的指针,请使用 bytes

(我想几分钟 NSData 文档将为您提供很好的服务)

You want one of the -dataWithBytes:length: or its variants:

NSData *d = [NSData dataWithBytes:data length:lengthOfDataInBytes];

which copies the bytes and you can then free(data). To save a copy, assuming data is allocated using malloc use:

NSData *d = [NSData dataWithBytesNoCopy:data length:lengthOfDataInBytes];

You should not call free on your buffer in this case, as the NSData instance will free it for you.

Note that all of these methods return an autoreleased instance, so you will probably have to retain it if you want to keep it around between threads (and aren't using GC). You can use the equivalent alloc/initWithBytes:... initializers instead.

To get a pointer to an NSData's contents, use bytes.

(I think a few minutes with the NSData documentation will serve you well)

情未る 2024-09-12 12:24:29

谢谢巴里,

我实际上选择了更简单的东西。

在指针周围放置一个 NSValue 包装器:

NSValue *value = [NSValue valueWithPointer:imageData];

将其放入字典中以返回到主线程:

[result setObject:value forKey:cubicFaceName];

回到主线程,当我处理完数据后,我将丢弃它:

uint8_t *bits = [value pointerValue];
free(bits);

干杯,
道格

Thanks Barry,

I actually went with something even simpler.

Put an NSValue wrapper around the pointer:

NSValue *value = [NSValue valueWithPointer:imageData];

Stuff it in a dictionary to be returned to the main thread:

[result setObject:value forKey:cubicFaceName];

Back on the main thread, when I'm done with the data I discard it:

uint8_t *bits = [value pointerValue];
free(bits);

Cheers,
Doug

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文