[英]How to pass a default numpy array argument to a function in pybind11?
[英]How to pass float to a pybind11 function expecting an int
我從 pybind11 文檔中復制了示例:
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.def("add", &add, "A function which adds two numbers");
}
像這樣構建它:
g++ -fPIC -shared -I/usr/include/python3.7 -o example.so example.cpp
然后:
$ python3
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from example import *
>>> add(1, 2)
3
>>> add(1.0, 2.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add(): incompatible function arguments. The following argument types are supported:
1. (arg0: int, arg1: int) -> int
Invoked with: 1.0, 2.0
>>>
我意識到我可以重寫add
以采用double
arguments ,然后在add
的主體內截斷它們。 但是有沒有辦法告訴 pybind11 可以將浮點數傳遞給 function (即使它需要int
參數)並讓它自動執行轉換?
根據文檔,相反(從 integer 類型轉換為double
)是隱式自動完成的。
默默地和隱式地截斷為int
是一件可怕的事情, pybind11
不會為你做這件事。 如果您必須允許,您可以為每個參數類型創建一個重載的 function,並讓double
變體代表您進行截斷(請記住,這可能不僅會丟失小數點后的精度; double
可以表示比任何 integer 類型,所以這些數字會發生壞事)。
一個粗略的例子是:
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add_int(int i, int j) {
return i + j;
}
int add_double_as_int(double i, double j) {
return add_int((int)i, (int)j);
}
PYBIND11_MODULE(example, m) {
m.def("add", &add_int, "A function which adds two integers");
m.def("add", &add_double_as_int, "A function which adds two floats after truncating to int");
}
在 C++ 級別,函數具有不同的名稱(您可以通過類似於使用 class 方法的示例進行創造性轉換來避免這種情況,但它幾乎不值得麻煩),但在 ZA7F5F35426B9274111FC923 級別,它們出現,作為具有文檔中描述的多個原型的單個 API。
C++ 是強類型的。 只有當它可以安全地完成時,它才會對基本類型進行自動類型轉換。 由於 integer 不能代表雙精度罐 C++ 無法自動執行轉換的每個值。 因此,您需要自己明確地進行轉換。 我不確定這是如何在 python 中完成的。 在 C++ 中,最好使用:
#include \<cmath\>
double dbl = 3.5;
int newval = std::round(dbl);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.