Pybind11 默认参数 numpy 数组或 None

Jav*_*ier 3 c++ python binding numpy pybind11

我正在包装一些 C++ 代码以从 Python 中使用它。我想调用一个带有参数的 C++ 函数,该参数可以采用另一个输入变量的None值或numpy.array相同大小的值。这是例子:

import example

# Let I a numpy array containing a 2D or 3D image
M = I > 0
# Calling the C++ function with no mask
example.fit(I, k, mask=None)
# Calling the C++ function with mask as a Numpy array of the same size of I
example.fit(I, k, mask=M)
Run Code Online (Sandbox Code Playgroud)

如何使用 pybind11 在 C++ 中进行编码?我有以下函数签名和代码:

void fit(const py::array_t<float, py::array::c_style | py::array::forcecast> &input, 
         int k,
         const py::array_t<bool, py::array::c_style | py::array::forcecast> &mask)
{
    ...
}

PYBIND11_MODULE(example, m)
{
    m.def("fit", &fit,
        py::arg("input"),
        py::arg("k"),
        py::arg("mask") = nullptr // Don't know what to put here?
    );
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Yix*_*ing 6

对于 C++17 std::optional,下面是一个应该可以工作的示例。对于早期版本的 C++,您可能需要向后移植optional.h并实现您自己的,optional_caster类似于pybind11/stl.h.

假设你想要这个功能:

def add(a, b=None):
    # Assuming a, b are int.
    if b is None:
        return a
    else:
        return a + b
Run Code Online (Sandbox Code Playgroud)

这是等效的 C++ pybind 实现:

m.def("add",
    [](int a, std::optional<int> b) {
        if (!b.has_value()) {
            return a;
        } else {
            return a + b.value();
        }
    },
    py::arg("a"), py::arg("b") = py::none()
);
Run Code Online (Sandbox Code Playgroud)

在 python 中,可以通过以下方式调用该函数:

add(1)
add(1, 2)
add(1, b=2)
add(1, b=None)
Run Code Online (Sandbox Code Playgroud)

对于numpy数组,只需修改示例中的std::optional<int>std::optional<py:array>即可。std::optional<py:array_t<your_custom_type>>