Boost.Python:__init__接受无参数

问题描述:

我有一个包含Boost.Python的C++值类型,它有一个NULL值的概念。包装代码的相关部分显示如下:Boost.Python:__init__接受无参数

class_<TCurrency> currency("TCurrency") 
    .def(init<long>()) 
    .def(init<const std::string&>()) 
    <...>; 

目前,试图通过使None__init__()方法来创建在Python NULL实例使C++构造函数接受常量字符串参考与无效被称为参考。 (&arg == NULL

是否有可能将None传递给构造函数并将其正常处理或至少在程序崩溃之前抛出一个有意义的异常?

使用Boost 1.36和Python 2.6.2。

如果使用None,那么重载将会传递NULL,但我不确定这会在角落情况下如何影响其他ctors。如果我将init<void*>列出,我也不会得到相同的无以字符串const &转换,您提到。使用Boost.Python 1.37和Python 2.6.2。

例子:

#include <iostream> 
#include <string> 

#include <boost/python.hpp> 


struct A { 
#define BODY { std::cout << __PRETTY_FUNCTION__ << '\n'; } 
    A() BODY 
    A(long) BODY 
    A(std::string const&) BODY 
    A(void* p) BODY 
#undef BODY 
}; 

BOOST_PYTHON_MODULE(ex) { 
using namespace boost::python; 
class_<A>("A") 
    .def(init<long>()) 
    .def(init<std::string const&>()) 
    .def(init<void*>()) 
; 
} 
 
>>> import ex 
>>> ex.A() 
A::A() 
<ex.A object at 0x839bf7c> 
>>> ex.A(42) 
A::A(long int) 
<ex.A object at 0x839bfcc> 
>>> ex.A("abc") 
A::A(const std::string&) 
<ex.A object at 0x839bf7c> 
>>> ex.A(None) 
A::A(void*) 
<ex.A object at 0x839bfcc> 

如果init<void*>被冷落:

 
>>> ex.A(None) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
Boost.Python.ArgumentError: Python argument types in 
    A.__init__(A, NoneType) 
did not match C++ signature: 
    __init__(_object*, std::string) 
    __init__(_object*, long) 
    __init__(_object*) 
+0

它似乎像应该有一个适配器或类似的,你应该能够申请到,例如,使A(无)使用默认ctor。我很高兴你问这个问题,我会期待更详细的答案。 (从别人..> 2009-12-02 07:29:53

+0

有趣。我真的不想修改原始的C++类来接受void *,但我试图在类之外定义一个__init__。它实际上并没有正确创建一个对象(这将成为另一个问题的主题),但至少我得到了一个Python tb而不是崩溃。好极了! =] – 2009-12-02 18:57:22