如何在boost python中公开一个接受变量参数的c++函数

How to expose a c++ function taking variable arguments in boost python

本文关键字:一个 变量 参数 函数 c++ boost python      更新时间:2023-10-16

我有一个接受可变数量参数的c++函数。

   char const* Fun(int num, ...)
   {
   ....//does some processing on the arguments passed
   }

Boost Python中暴露这个函数的代码如下:

    using namespace boost::python;
    BOOST_PYTHON_MODULE( lib_boost )
   {
       def( "Fun", Fun );
   }

在编译这段代码时会产生以下错误

从/boost_1_42_0/boost/python/data_members.hpp:15,从/boost_1_42_0/提高/python/class.hpp: 17日从/boost_1_42_0/提高/python.hpp: 18日从Lib_boost.h: 3,from Lib_boost.cpp:1:/boost_1_42_0/boost/python/make_function.hpp: In function'boost::python::api::object boost::python::make_function(F) [with F = .const char * () (int , ...)]':/boost_1_42_0/提高/python/def.hpp: 82:
由` boost::python::api::object `实例化boost::python::detail::make_function1(T,…)[with T = const char
]() (int , ...)]'/boost_1_42_0/提高/python/def.hpp: 91:实例化from ` void boost::python::def(const char, Fn) [with Fn = const char* . .()(int,…)]' Lib_boost.cpp:540:从这里实例化/boost_1_42_0/boost/python/make_function.hpp:104: error: invalid从'const char ()(int,…)'到'const char的转换()(int)/boost_1_42_0/boost/python/make_function.hpp:104: error:
初始化boost::mpl::vector2的参数1boost::python::detail::get_signature(RT (
)(T0), void*) [with RT =const char*, T0 = int]'

我对上面错误信息的理解是boost python无法识别接受变量参数的函数(从'const char* ()(int,…)'到'const char (*)(int)'的无效转换)

使用固定/已知参数集公开函数与使用可变参数的函数不同。如何暴露一个函数与变量参数?

我发现处理可变参数的最好方法是使用raw_function。通过这种方式,您可以完全控制将c++参数转换为Python对象:

包装:

using namespace boost::python;
object fun(tuple args, dict kwargs)
{
    char* returned_value;
    for(int i = 0; i < len(args); ++i) {
        // Extract the args[i] into a C++ variable,
        // build up your argument list
    }
    // build your parameter list from args and kwargs 
    // and pass it to your variadic c++ function
    return str(returned_value);
}

声明:

def("fun", raw_function(fun, 1) );

raw_function接受两个参数:函数指针和最小参数数。

如果您使用的是c++11,那么以下操作可以工作(在g++-4.8.2上测试)

#include <boost/python.hpp>
#include <boost/python/list.hpp>
#include <vector>
#include <string>
#include <cstdarg>
#include <cassert>
using namespace boost::python;
template <int... Indices>
struct indices
{
    using next = indices<Indices..., sizeof...(Indices)>;
};
template <int N>
struct build_indices
{
    using type = typename build_indices<N-1>::type::next;
};
template <>
struct build_indices<0>
{
    using type = indices<>;
};
template <int N>
using BuildIndices = typename build_indices<N>::type;
template <int num_args>
class unpack_caller
{
private:
    template <typename FuncType, int... I>
    char * call(FuncType &f, std::vector<char*> &args, indices<I...>)
    {
        return f(args.size(), args[I]...);
    }
public:
    template <typename FuncType>
    char * operator () (FuncType &f, std::vector<char*> &args)
    {
        assert( args.size() <= num_args );
        return call(f, args, BuildIndices<num_args>{});
    }
};
//This is your function that you wish to call from python
char * my_func( int a, ... )
{
    //do something ( this is just a sample )
    static std::string ret;
    va_list ap;
    va_start (ap, a);
    for( int i = 0; i < a; ++i)
    {
        ret += std::string( va_arg (ap, char * ) );
    }
    va_end (ap);
    return (char *)ret.c_str();
}
std::string my_func_overload( list & l )
{
    extract<int> str_count( l[0] );
    if( str_count.check() )
    {
        int count = str_count();
        std::vector< char * > vec;
        for( int index = 1; index <= count; ++index )
        {
            extract< char * > str( l[index] );
            if( str.check() )
            {
                //extract items from list and build vector
                vec.push_back( str() );
            }
        }
        //maximum 20 arguments will be processed.
        unpack_caller<20> caller;
        return std::string( caller( my_func, vec ) );
    }
    return std::string("");
}
BOOST_PYTHON_MODULE(my_module)
{
    def("my_func", my_func_overload )
    ;
}
在python中

:

Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_module as m
>>> m.my_func([5, "my", " first", " five", " string", " arguments"])
'my first five string arguments'
>>>

在这个例子中"char * my_func(int a,…)简单地连接所有字符串参数并返回结果字符串。

您可以通过将参数视为可选来实现,只要您知道最大计数可以是多少。详见:https://wiki.python.org/moin/boost.python/FunctionOverloading