Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a C float array in an NSDictionary

I am trying to store a c-float array in an NSDictionary to use later.
I was initially using an NSArray to store the C-data but NSArray is to slow for my intentions.

I am using the following code to wrap the arrays in the NSDictionary:

[self.m_morphPositions setObject:[NSValue valueWithBytes:&positionBuff objCType:@encode(float[(self.m_countVertices * 3)])] forKey:fourCC];

And retrieving the C-Float array using:

float posMorphs[(self.m_countVertices*3)];

NSValue *posValues = [self.m_morphPositions objectForKey:name];

[posValues getValue:&posMorphs];

When I retireve the array, the values are all set to 0.0 for each index which is wrong.

How can I fix this?

like image 900
samb90 Avatar asked Apr 06 '13 13:04

samb90


3 Answers

I also think that NSData is probably the best solution here. But just if anybody is interested: You cannot use @encode with a variable sized array, because it is a compiler directive. Therefore

@encode(float[(self.m_countVertices * 3)])

cannot work. Actually the compiler creates the encoding for a float array of size zero here, which explains why you get nothing back when reading the NSValue.

But you can create the type encoding string at runtime. For a float array, the encoding is [<count>^f] (see Type Encodings), so the following would work:

const char *enc = [[NSString stringWithFormat:@"[%d^f]", (self.m_countVertices * 3)] UTF8String];
NSValue *val = [NSValue valueWithBytes:positionBuff objCType:enc];
like image 122
Martin R Avatar answered Oct 21 '22 06:10

Martin R


NSValue is probably intented for scalar values, not arrays for them. In this case, using NSData should be much easier

NSData* data = [NSData dataWithBytes:&positionBuff length:(self.m_countVertices * 3 * sizeof(float))];
[data getBytes:posMorphs length:(self.m_countVertices * 3 * sizeof(float))];

Another solution is to allocate the array on the heap and use NSValue to store the pointer.

like image 25
Sulthan Avatar answered Oct 21 '22 05:10

Sulthan


You can feed the bytes into an NSDictionary if they're wrapped in an NSData.

If you want to skip that, you would use an NSMapTable and NSPointerFunctionsOpaqueMemory (or MallocMemory) for the value pointer functions.

like image 1
iluvcapra Avatar answered Oct 21 '22 07:10

iluvcapra