Boost.python 重载 numpy 数组和 python 列表的构造函数

发布于 2024-11-01 22:23:56 字数 110 浏览 2 评论 0原文

给定一个使用 Boost.Python 公开的 C++ 类,如何公开两个构造函数:

  • 一个采用 numpy 数组,
  • 另一个采用 python 列表?

Given a C++ class exposed with Boost.Python, how do I expose two constructors:

  • one that takes a numpy array, and
  • another that takes a python list?

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

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

发布评论

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

评论(1

柠栀 2024-11-08 22:23:56

我不是 100% 理解你的意思,但我假设你想要一个构造函数接受一个 Python 列表,另一个构造函数接受一个 numpy 数组。有几种方法可以解决这个问题。最简单的方法是使用 make_constructor 函数并重载它:

using boost;
using boost::python;

shared_ptr<MyClass> CreateWithList(list lst)
{
    // construct with a list here
}

shared_ptr<MyClass> CreateWithPyArrayObject(PyArrayObject* obj)
{
    // construct with numpy array here
}


BOOST_PYTHON_MODULE(mymodule)
{
    class_<MyClass, boost::noncopyable, boost::shared_ptr<MyClass> >
        ("MyClass", no_init)
        .def("__init__", make_constructor(&CreateWithList))
        .def("__init__", make_constructor(&CreateWithPyArrayObject))
}

您可以更聪明,在构造函数中使用任意类型/数量的参数。这需要一点巫毒才能完成。请参阅http://wiki.python.org/moin/boost。 python/HowTo#A.22Raw.22_constructor 用于将原始函数定义公开为构造函数的方法。

I'm not a 100% on what you mean, but I'm assuming that you want to have a constructor taking a Python list and another one taking a numpy array. There are a couple of ways to go about this. The easiest way is by using the make_constructor function and overloading it:

using boost;
using boost::python;

shared_ptr<MyClass> CreateWithList(list lst)
{
    // construct with a list here
}

shared_ptr<MyClass> CreateWithPyArrayObject(PyArrayObject* obj)
{
    // construct with numpy array here
}


BOOST_PYTHON_MODULE(mymodule)
{
    class_<MyClass, boost::noncopyable, boost::shared_ptr<MyClass> >
        ("MyClass", no_init)
        .def("__init__", make_constructor(&CreateWithList))
        .def("__init__", make_constructor(&CreateWithPyArrayObject))
}

You can be even more clever and use an arbitrary type/number of arguments in your constructor. This requires a bit of voodoo to accomplish. See http://wiki.python.org/moin/boost.python/HowTo#A.22Raw.22_constructor for a way to expose a raw function definition as a constructor.

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