Reputation: 2559
I am calling a C++ method from Objective C. I need to pass a float value as parameter. Here is the code:
c++ method:
void printValue(float a){
NSLog(@"Value of a: %5.2f",a); // I am using NSLog here. It works
}
I have the directive, extern "C" in the c++ file. Also using .mm extension for the c++ file
I call this method from Objective C class like this:
printValue(3.1); // 3.1 is a sample value
I am getting Value of a: 0.00
. If I change the (float a)
to (double a)
I get correct value 3.10.
I tried casting the value to float when calling:
printValue((float)3.1);
This also gives 0.00
How can I explain this?
Upvotes: 1
Views: 635
Reputation: 81868
C's calling conventions say that when passing arguments to a variadic argument function (a function like NSLog with a ... at the end of the parameter list) each float
must be converted and passed as a double
.
I expect that this is not the case with C++ (but I don't really know). Anyway, as NSLog
expects all floating point types to be doubles it's safest to do the conversion explicitly:
NSLog(@"Value of a: %5.2f", (double)a);
Another idea: If the compiler says something about a missing function declaration regarding NSLog
the problem could also be that it does not do the conversion to double
as expected by the variadic arguments because it does not see the function's declaration.
Upvotes: 1