Storing a C struct in CFMutableDictionary

南笙酒味 提交于 2019-12-22 08:12:56

问题


Since there is no counterpart to NSValue in Core Foundation, how are we supposed to store C structs in a CFMutableDictionary?


回答1:


First, you can put an NSvalue in a CFMutableDictionary as-is, so the answer is "use NSValue." But I assume the rest of your question is "without using any Cocoa objects." In that case, just create a non-retaining CFMutableDictionary, and you can put any pointer you want into it. See "Defining Custom Collection Callbacks" for some example code. I use these a lot.

Remember that these still have to be pointers, so you're going to have to allocate your structs on the heap, not the stack. And that means that memory management is now your problem. Of course you could create a custom set of callbacks that do whatever you want, so if you're using boost or something else with its own ref-counting system, you can still implement that with CFMutableDictionary.

And of course you can replace the struct with a small data object. That's usually a lot easier. But different problems need different solutions.




回答2:


CFMutableDictionary

CFDictionaryAddValue A CFType object or a pointer value to add to the dictionary.

you just pass a pointer to your struct.



来源:https://stackoverflow.com/questions/1203726/storing-a-c-struct-in-cfmutabledictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!