在python3中使用ctypes得到'nan',其中一个float预计会被关闭[关闭]

问题描述 投票:0回答:1

这是我的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

我糊涂了

python c ctypes
1个回答
2
投票

你返回intgetbmi()所以你的res被铸造到int所以1.6002 / 75 / 75 = 0.00028448,所以演员产生一个0。但你告诉python返回类型是float所以python将int解释为float

float getbmi(float h, float w);

float getbmi(float h, float w) {
  return w / h / h;
}
© www.soinside.com 2019 - 2024. All rights reserved.