Boost.Python从typ创建句柄

2024-06-16 10:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在将C++代码暴露到Python的一些地方,我需要使用^ {< CD1>}。如果我有一个boost::python::class_对象的实例,我可以对它调用ptr()。但是如果我有那种类型呢?在

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


Tags: 对象实例代码类型列表地方classbases
1条回答
网友
1楼 · 发布于 2024-06-16 10:53:16

给定C++类型^ {CD1>},可以创建一个^{}对象,然后查询到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);
}

下面是一个完整的示例demonstrating在Boost.Python注册表:

^{pr2}$

输出:

<class 'Spam'>

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

相关问题 更多 >