簡體   English   中英

Object 在 Python 中通過 Pybind11 創建的 Object 未被 ZF6F87C3FDCF8B3C2FC2F07F 函數識別為派生的 class

[英]Object created in Python via Pybind11 not recognized as a derived class by C++ functions

重現該問題的最少代碼如下:

aaa.hpp

#include <string>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <cmath>
#include <cassert>
#include <utility>


template <typename D>
class BaseClass{
    /* The base class. */
protected:
    bool skip_nan = true;
};

template <typename D>
class DerivedClass : public BaseClass<D>{
public:
    explicit DerivedClass(bool skip_nan_){ this->skip_nan = skip_nan_; }
};

aaa_py.cpp

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "aaa.hpp"
namespace py = pybind11;


template <typename D>
void fff(BaseClass<D>& rs){

}


PYBIND11_MODULE(aaa_py, m) {
    m.def("fff_float", &fff<float>);
    py::class_<DerivedClass<float>>(m, "DerivedClass_float").def(py::init<bool>(), py::arg("skip_nan")=true);
}

test.py

import aaa_py as rsp
ds = rsp.DerivedClass_float()
rsp.fff_float(ds)

錯誤:

Traceback (most recent call last):
  File "usage_example_python.py", line 8, in <module>
    rsp.fff_float(ds)
TypeError: fff_float(): incompatible function arguments. The following argument types are supported:
    1. (arg0: BaseClass<float>) -> None

Invoked with: <aaa_py.DerivedClass_float object at 0x000002C9EAF57308>

基本上錯誤是說 function fff_float期望有人來自BaseClass<float> ,但收到DerivedClass<float> 如果我將 function 更改為接受DerivedClass<D>& ,則不會出現錯誤。 或者,如果我直接在 c++ 中創建DerivedClass<float>的實例並將其傳遞給float_fff ,也不會有任何問題。 因此,問題似乎在於,對於在 Python 中創建的 object,不知何故,有關其基礎 class 的信息丟失了。 我該如何處理?

您需要在 Python 中聲明BaseClass<float>並告訴 pybind11 DerivedClass_float擴展它。

PYBIND11_MODULE(MyModule, m)
{
    m.def("fff_float", &fff<float>);

    // declare base class - this simply expose to Python, it's impossible to
    // construct a BaseClass_float in Python since no constructor is provided
    py::class_<BaseClass<float>>(m, "BaseClass_float");

    // tell pybind11 that DerivedClass<float> extends BaseClass<float>
    py::class_<DerivedClass<float>, BaseClass<float>>(m, "DerivedClass_float")
    //                              ^^^^^^^^^^^^^^^^
        .def(py::init<bool>(), py::arg("skip_nan") = true);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM