Question

I have a function that returns a double in a void *. However it seems to loose the pointer or seems unable to get the value as it returns 0 once out of the function.

How would you create a double and assign it to be the value of a void * and then return it without it being out of scope.

The idea of this function is it will convert a object from Objective-C to something in C++ but not everything in C++ is an object such as double, where it is in Objective C.

void * IDToSTD (id anObject){

void * stdObject = NULL;

if ([anObject class] == [PFObject class]) {
    stdObject = BridgePFObject((void *)CFBridgingRetain(anObject));
    return stdObject;
}

CFTypeRef inTypeRef = (__bridge CFTypeRef)anObject;
CFTypeID type = CFGetTypeID(inTypeRef);

if (type == CFArrayGetTypeID()) {
    std::vector<void *> arr = NSArrayToSTDVector([(NSArray *)anObject copy]);
    stdObject = &arr;
} else if (type == CFDictionaryGetTypeID()) {
    std::map<std::string, void *> dict = NSDictionaryToSTDMap([(NSDictionary *)anObject copy]);
    stdObject = &dict;
} else if (type == CFStringGetTypeID()) {
    stdObject = (char *)[(NSString *) anObject cStringUsingEncoding:NSUTF8StringEncoding];
} else if (type == CFNumberGetTypeID()) {
    double *value = (double *)malloc(sizeof(double *));
    *value = [(NSNumber *)anObject doubleValue];
    stdObject = value;
} else {
    [NSException raise:@"Invalid object value" format:@"Object must be of basic Core Foundation or Parse Type, Object Type is: %@", NSStringFromClass([anObject class])];
}

return stdObject;

}

Was it helpful?

Solution

I assume that by putting a double in a void-pointer, you actually mean: taking the address of the double, then assinging that double-pointer to the void-pointer.

Assigning the double directly to the pointer certainly gives problems in 32-bit applications (double=8 bytes, pointer=4 bytes).

What you can do is to declare a double variable as static within your function. Then return a pointer to that static double variable. However, as soon as somebody else (other thread?) will call the function, the static double will be overwritten and the first caller will lose the value.

The thread-problem can be solved by using thread local storage. In Visual Studio, you can use "declspec(thread)" to make the static variable static-per-thread. But this still doesn't solve the problem if you cannot guarantee that the same thread will call the same function when the first one didn't grab the double value out of the void-pointer yet.

You could consider passing a double reference as argument to the function, and then return a void-pointer to the given reference. That way, the caller provides its own double variable, which the function then fills and returns a pointer to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top