在需要浮点数的 python3 中使用 ctypes 时得到 'nan'

Got 'nan' when using ctypes in python3 where a float is expected

这是我的bmi.c

#include<stdio.h>

float height;
float weight;
int getbmi(float h , float w);

int main(){
    return 0;
}

int getbmi(float h , float w)
{
     //float h , w;
    float res;

    res = w/h;
    res = res/h;
    return res;
 }

我正在这样编译:

gcc -shared -Wl,-soname,adder -o bmi.so -fPIC bmi.c

那么这是我的getbmi.py

from ctypes import *

bmi = CDLL('./bmi.so')

h = c_float(1.6002)
w = c_float(75)

getbmi = bmi.getbmi
getbmi.restype = c_float
print(getbmi(h, w))

当我 运行 getbmi.py 我只得到一个输出:nan

我很困惑

你 return 一个 intgetbmi() 所以你的 res 被转换为 int 所以 1.6002 / 75 / 75 = 0.00028448, 所以转换产生一个0。但是你告诉 python return 类型是 float 所以 python 将 int 解释为 float.

float getbmi(float h, float w);

float getbmi(float h, float w) {
  return w / h / h;
}