为什么pybind11将double转换为int?

时间:2020-08-01 10:10:40

标签: python c++ pybind11

我创建了.pyd文件:

#include <pybind11/pybind11.h>
#include <iostream>
#include <typeinfo>
namespace py = pybind11;
int add(int num) {
    float a = 1.0;  
    for (int i = 0; i <= num; i = i + 1) {
        a = (a + i)/a;
    }        
    std::cout << "dll is typing: " << a << '\n';
    std::cout << typeid(a).name() << std::endl;
    return a;
}
PYBIND11_MODULE(py_dll, m) {
    m.doc() = "pybind11 py_dll plugin"; // optional module docstring
    m.def("add", &add, "Add function", py::arg("num"));
}

我从python调用它:

import py_dll
num = 500
a = py_dll.add(num)
print ('python is typing: ', a)

它打印:

enter image description here

为什么数字变成整数?我说的是22。我希望它是浮动22.8722

1 个答案:

答案 0 :(得分:1)

此功能

int add(int num)

采用int作为参数并返回int。 “问题”与pybind无关。试试看:

int main() {
    auto x = add(42);
    std::cout << "return value: " << x << '\n';
    std::cout << typeid(x).name() << std::endl;
}

如果函数应返回float,则必须声明它返回float

float add(int num)
相关问题