2016-07-06 89 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答案。