导出返回引用的函数

2 投票
2 回答
795 浏览
提问于 2025-04-16 14:04

我想把一个用C++写的函数导出到Python模块中,这个模块使用了boost.python库。

Vec2<Type> &normalize () 
Type dot(const Vec2<Type> &vector) const

这些是模板类 Vec2 的成员。下面是我的导出代码:

bp::class_< Vec2<int> >("Vec2i", bp::init<int, int>())
    .def("Length", &Vec2<int>::length)
    .def("Dot", &Vec2<int>::dot, bp::return_internal_reference<>());
    //.def("Normalize", &Vec2<int>::normalize);

Length 方法编译成功,但 DotNormalize 在编译时都出现了同样的错误:

 error: no matching function for call to ‘boost::python::class_<Vec2<int> >::def(const char [4], <unresolved overloaded function type>, boost::python::return_internal_reference<>)’

我哪里做错了?


更新

真实的类名是: CL_Vec<Type>,这里是 文档

2 个回答

2

当编译器说:

<unresolved overloaded function type>

看看你的成员指针或者函数指针(比如 &Vec2::dot),确认它是不是指向一组重载函数(应该是的)。在这种情况下,你可能需要明确地使用 static_cast<> 来转换成特定的成员指针或函数指针类型,包括函数的参数类型。

4

如果你查看一下 vec2.h(或者你链接的文档),你会发现 dotnormalize 这两个函数是重载的,也就是说它们有多个版本,因为它们还有 static 版本。

你可以通过使用一些函数指针来解决这个问题:

Vec2<int> &(Vec2<int>::*norm)() = &Vec2<int>::normalize;

然后在 def 中使用它,具体的解释可以在 这里找到。

撰写回答