指向 swig(或 Boost::Python)中成员的指针

发布于 2024-08-11 21:56:03 字数 827 浏览 1 评论 0原文

我从我的 Python C++ 应用程序中进行了一些绑定。

问题是我使用指向成员的指针(它用于计算最短路径并给出要最小化的属性作为参数)。

这是 C++ 签名:

std::vector<Path> martins(int start, int dest, MultimodalGraph & g, float Edge::*)

这就是我所做的(根据我在文档中的理解):

%constant float Edge::* distance = &Edge::distance;

这是我从 python 调用我的函数的方式:

foo.martins(0, 1000, g, foo.distance)

这是我得到的错误:

NotImplementedError: Wrong number of arguments for overloaded function 'martins'.
Possible C/C++ prototypes are:
martins(int,int,MultimodalGraph &,float Edge::*)

我有一个使用默认第四个参数的重载方法,而且效果很好。

那么是否可以在 swig 中使用指向成员的指针? 如果可以,有什么技巧呢?如果不是,最优雅的工作方式是什么?

感谢您的帮助!

更新:如果有人知道 Boost::python 是否确实可以做到这一点,我会切换到它。

I made some bindings from my C++ app for python.

The problem is that I use pointers to members (It's for computing shortest path and giving the property to minimize as parameter).

This is the C++ signature:

std::vector<Path> martins(int start, int dest, MultimodalGraph & g, float Edge::*)

This is what I did (from what I understood in the doc):

%constant float Edge::* distance = &Edge::distance;

This is how I call my function from python:

foo.martins(0, 1000, g, foo.distance)

And this is the error I get:

NotImplementedError: Wrong number of arguments for overloaded function 'martins'.
Possible C/C++ prototypes are:
martins(int,int,MultimodalGraph &,float Edge::*)

I have an overloaded method that uses a default 4th paramaters, and it works perfectly.

So is it possible to use pointers to members with swig? If yes, what's the trick? If no, what would be the most elegant way to work arround?

Thank you for your help!

UPDATE: if someone knows if Boost::python does it for sure, I'll switch to it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不打扰别人 2024-08-18 21:56:03

不知道 SWIG,但在 boost::python 中你可以编写一个包装器:

bool foo(int x, float* result);

boost::python::tuple foo_wrapper(int x)
{
    float v;
    bool result = foo(x, &v);
    return boost::python::make_tuple(result, v);
}

BOOST_PYTHON_MODULE(foomodule)
{
    def("foo", &foo_wrapper);
}

在 python 中你会:

result, v = foomodule.foo(x)

因为在 Python 中浮点数是不可变的,所以你实际上不能将浮点数传递给方法并期望该方法改变浮点数value,因此我们调整代码以返回值的元组。

Don't know about SWIG, but in boost::python you can write a wrapper:

bool foo(int x, float* result);

boost::python::tuple foo_wrapper(int x)
{
    float v;
    bool result = foo(x, &v);
    return boost::python::make_tuple(result, v);
}

BOOST_PYTHON_MODULE(foomodule)
{
    def("foo", &foo_wrapper);
}

And in python you would:

result, v = foomodule.foo(x)

Since in Python floats are immutable, you can't actually pass one to a method and expect the method to change the float value, so we adapt the code to return a tuple of values instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文