简体   繁体   English

如何将默认的numpy数组参数传递给pybind11中的函数?

[英]How to pass a default numpy array argument to a function in pybind11?

I am defining a method that takes py::array_t< double > and py::array_t< bool > as arguments. 我正在定义一个以py :: array_t <double>和py :: array_t <bool>作为参数的方法。 How can I tell pybind11 to default those arguments to an array of my choice? 如何告诉pybind11将这些参数默认为我选择的数组? (say np.array([0, 0, 0])) (例如np.array([0,0,0]))

I have tried adding the default via "Argument"_a = py::array_T({0, 0, 0}) but when I call it itells me 'array has incorrect number of dimensions: 3; 我曾尝试通过“ Argument” _a = py :: array_T({0,0,0})添加默认值,但是当我调用它时,它告诉我“数组的维数不正确:3; expected 1' 预期1'

m.def("foo", [](py::array_t<double> Arg1,                        
                py::array_t<bool> Arg2){

        auto bar = Arg1.unchecked<1>();
        auto bar2 = Arg2.unchecked<1>();

                    '''other simple code that doesn't alter bar or bar2'''

        return bar;
    },
    "Arg1"_a,
    "Arg2"_a = py_array<bool> ({0, 0, 0})
);

The problem is that value of your default argument is 3d array with zero-length dimensions, instead of 1d array of three elements. 问题在于您的默认参数的值是零长度尺寸的3d数组,而不是三个元素的1d数组。

The constructor you are calling with py_array<bool> ({0, 0, 0}) : 您使用py_array<bool> ({0, 0, 0})调用的构造函数:

    explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
        : array_t(private_ctor{}, std::move(shape),
                ExtraFlags & f_style ? f_strides(*shape, itemsize()) : c_strides(*shape, itemsize()),
                ptr, base) { }

https://github.com/pybind/pybind11/blob/c9d32a81f40ad540015814edf13b29980c63e39c/include/pybind11/numpy.h#L861 https://github.com/pybind/pybind11/blob/c9d32a81f40ad540015814edf13b29980c63e39c/include/pybind11/numpy.h#L861

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM