boost-python:如何提供自定义构造函数包装函数? [英] boost-python: How do I provide a custom constructor wrapper function?

查看:140
本文介绍了boost-python:如何提供自定义构造函数包装函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用boost-python为名为CppClass的C ++类创建python绑定.必要时,我可以通过对参数进行预处理的小型包装函数将调用路由到普通"成员函数(例如,从python args中提取C ++类型),例如:

I'm using boost-python to create python bindings for a C++ class named CppClass. When necessary, I can route calls to "normal" member functions through little wrapper functions that preprocess the arguments (e.g. extract C++ types from the python args), like so:

class CppClass
{
public:
    CppClass(SpecialParameters p);
    void doSomething(int x, float y);
};

using namespace boost::python; // For extract, tuple, init, class_, etc.

class WrapperFuncs
{
public:
    static void doSomething(CppClass & c, tuple t)
    {
        // Special extraction: Convert python arg ( a tuple) into C++ args.
        int x = extract<int>(t.attr("__getitem__")(0));
        float y = extract<float>(t.attr("__getitem__")(1));
        c.doSomething(x,y);
    }
};

class_<CppClass, boost::shared_ptr<CppClass> >
    ("CppClass", init<SpecialParameters>())
    .def("doSomething", &WrapperFuncs::doSomething, (arg("t")))

但是对于CppClass 构造函数,我该怎么做?

But how do I do the same for the CppClass constructor?

推荐答案

使用no_init,然后使用boost::python::make_constructor()使用.def表示__init__.

Use no_init followed by a .def for __init__ using boost::python::make_constructor().

class WrapperFuncs
{
public:
    static boost::shared_ptr<CppClass> initWrapper( object const & p )
    {
        SpecialParameters sp = ... // do complicated extraction here.
        return boost::shared_ptr<CppClass>( new CppClass(sp) );
    }

    static void doSomething(CppClass & c, tuple t) { /*...*/ }
};

class_<CppClass, boost::shared_ptr<CppClass> >
    ("CppClass", no_init)
    .def("__init__", make_constructor(&WrapperFuncs::initWrapper))
    .def("doSomething", &WrapperFuncs::doSomething, (arg("t")))

Python Wiki的本部分解释了如何执行此操作,但是它对我不太有用,因为它没有提到no_init.就我而言,no_init是必需的.

This section of the python wiki explains how to do this, but it didn't quite work for me because it didn't mention no_init. In my case, no_init was required.

这篇关于boost-python:如何提供自定义构造函数包装函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆