Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ / Objective-C++ - How can I store a C++ variable in an NSDictionary?

I have a C++ variable of type std::vector<std::bitset<128> > which is defined and populated in a C++ class (which is called from my Objective-C++ class.)

I would like to store this object in an NSDictionary - or some equivalent of. I clearly can't simply add the std::vector<std::bitset<128> > to the NSDictionary because it's not of type id.

So my question is this: how can I achieve the same concept? How can I store a std::vector<std::bitset<128> > in a dictionary of sorts? Can I wrap the vector object in an id type somehow? Even if it's not a direct dictionary, is there another method I could use? I also need this to be mutable, so I can add key/object's at runtime.

I'v seen std::map<std::string, std::string>, but I'm not sure if it's what I'm looking for. Nor have I found any examples on it being mutable.

Does anyone have any idea how to achieve this?

like image 748
Brett Avatar asked Jan 31 '14 19:01

Brett


2 Answers

Actually NSValue seems to be the solution. @Taum's advice is correct for some cases (when you store your objects somewhere and sure your pointers are working). In case you've created some object and it's lifetime is limited, but you need to push this object further, use another NSValue method

std::vector<std::bitset<128>> cppVector;
NSValue *value=[NSValue valueWithBytes:&cppVector objCType:@encode(std::vector<std::bitset<128>>)];

When you need to get this value back:

std::vector<std::bitset<128>> cppVector;
[value getValue:&cppVector];

That works perfectly for simple structs too.

like image 98
Daniyar Avatar answered Nov 03 '22 21:11

Daniyar


You could store a pointer to it in a NSValue object. You'll just have to be careful about what owns the std::vector and when it should be free'd.

Store with:

std::vector<std::bitset<128>> *cppVector = myCppObject->methodReturningVector();
NSValue *value = [NSValue valueWithPointer:cppVector];
[myObjcDictionary setObject:value forKey:@"myKey"];

Get C++ object back with:

NSValue *value = [myObjcDictionary objectForKey:@"myKey"];
std::vector<std::bitset<128>> *cppVector = [value pointerValue]
like image 37
Taum Avatar answered Nov 03 '22 23:11

Taum