2016-07-06 90 views
2
创建句柄

在一些将C++代码暴露给python的地方,我需要使用PyObject*。如果我有一个boost::python::class_对象的实例,我可以在其上调用ptr()。但是如果我只有这种类型呢?Boost.Python从类型

基本上,给定类型列表boost::python::bases<A, B, C>,我想将其转换为boost::python::tuple的实例,我可以将其传递到PyErr_NewExceptionWithDoc()之类的实例中。这可能吗?

+0

回想起来,即使这是可能的,创建一个从Python异常类型和Boost.Python“class_”继承的python类型显然是不可能的。所以我想这比实用性更好奇。 – Barry

回答

1

给定一个C++类型T,可以创建一个boost::python::type_id对象,然后查询Boost.Python注册表中的注册信息。如果在注册表中找到一个条目,那么就可以用它来获取句柄为T类型创建的Python类:

/// @brief Get the class object for a wrapped type that has been exposed 
///  through Boost.Python. 
template <typename T> 
boost::python::object get_instance_class() 
{ 
    // Query into the registry for type T. 
    namespace python = boost::python; 
    python::type_info type = python::type_id<T>(); 
    const python::converter::registration* registration = 
    python::converter::registry::query(type); 

    // If the class is not registered, return None. 
    if (!registration) return python::object(); 

    python::handle<PyTypeObject> handle(python::borrowed(
    registration->get_class_object())); 
    return python::object(handle); 
} 

这里是定位在一个Python类对象的完整范例demonstrating Boost.Python的注册表:

#include <boost/python.hpp> 
#include <iostream> 

/// @brief Get the class object for a wrapped type that has been exposed 
///  through Boost.Python. 
template <typename T> 
boost::python::object get_instance_class() 
{ 
    // Query into the registry for type T. 
    namespace python = boost::python; 
    python::type_info type = python::type_id<T>(); 
    const python::converter::registration* registration = 
    python::converter::registry::query(type); 

    // If the class is not registered, return None. 
    if (!registration) return python::object(); 

    python::handle<PyTypeObject> handle(python::borrowed(
    registration->get_class_object())); 
    return python::object(handle); 
} 

struct spam {}; 

int main() 
{ 
    Py_Initialize(); 

    namespace python = boost::python; 
    try 
    { 
    // Create the __main__ module. 
    python::object main_module = python::import("__main__"); 
    python::object main_namespace = main_module.attr("__dict__"); 

    // Create `Spam` class. 
    // >>> class Spam: pass 
    auto spam_class_object = python::class_<spam>("Spam", python::no_init); 
    // >>> print Spam 
    main_module.attr("__builtins__").attr("print")(get_instance_class<spam>()); 
    // >>> assert(spam is spam) 
    assert(spam_class_object.ptr() == get_instance_class<spam>().ptr()); 
    } 
    catch (python::error_already_set&) 
    { 
    PyErr_Print(); 
    return 1; 
    } 
} 

输出:

<class 'Spam'> 

有关更多类型的相关功能,例如接受类型对象isissubclass,请参见this答案。