简体   繁体   中英

Passing float values from objective C to C++ methods

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM