python - 在需要 float 的 python3 中使用 ctypes 时得到 'nan'

标签 python c ctypes

<分区>

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

我很困惑

最佳答案

你用 getbmi() 返回一个 int 所以你的 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;
}

关于python - 在需要 float 的 python3 中使用 ctypes 时得到 'nan',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853770/

相关文章:

python - 获取字典python中所有唯一的辅助键

c - 在研究缓冲区溢出时我应该使用哪个版本的 GCC 或标志?

c - 注册一个函数处理程序

Python3k ctypes printf

c++ - 导入 ctype;在 C++ 应用程序中嵌入 python

Python ctypes 堆栈损坏

python - 在 django/selenium Web 测试中创建预认证 session

python - 根据日期信息计算工作日信息

python - 使用 beautifulsoup python 在 h3 和 p 标签中抓取文本

c - 读取行 C : force return of certain text in readline()