我有一个C++类,其中包含一个使用boost-python向python公开的纯虚方法。我从C++调用虚函数,并假设虚函数是用python实现的。如果实现了函数,那么一切都会正常工作,但是如果没有实现,我会得到一个讨厌的异常。
我正在尝试找到一种方法来检测方法是否真的实现了,而不是在装入类时调用
大致代码如下所示
#include <boost/python.hpp>
using namespace boost::python;
public Foo {
public:
void func() = 0;
}
class PyFoo : public Foo, public boost::python::wrapper<Foo> {
public:
void func() override {
get_override("func")();
}
};
BOOST_PYTHON_MODULE(example)
{
using namespace boost::python;
class_<PyFoo>, boost::noncopyable>("Foo")
.def("func", pure_virtual(&PyFoo::func))
;
}
void create {
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
std::string overrideCommand(
R"(
import example
class MyFoo(example.Foo):
def __init__(self):
example.Foo.__init__(self)
# virtual function in C++. (Should be defined)
# def func(self):
# print('func called')
)");
boost::python::exec(overrideCommand.c_str(), main_namespace);
result = eval("MyFoo()", main_namespace);
// Can I detect if 'result' has func implemented? If I call it and it
// is not defined death results. I have tried:
object attr = result.attr("func");
// but attr always seems to be set even if there is no function,
// I think from the base class Foo.
// This is the call:
Foo& t = extract<Foo&>(result);
t.func();
}发布于 2019-02-08 02:53:56
您可以使用PyCallable_Check。
if (!PyCallable_Check(result.func()))
{
PyErr_SetString(PyExc_TypeError, error_msg.str().c_str());
python::throw_error_already_set();
}发布于 2019-02-09 05:46:42
我找到了一个解决方案。可行,而不是优雅。我添加了这个方法:
bool isThere() {
auto obj = get_override("func");
return PyCallable_Check(obj.ptr());
}敬FooPy。然后:
FooPy& t = extract<FooPy&>(result);
t.isThere();https://stackoverflow.com/questions/54579420
复制相似问题