Python C API - 如何从 PyObject 构造对象
Python C API - How to construct object from PyObject
我想知道是否有一种很好的"本机"方法来构造给定已知类型的PyObject*
的对象。
这是我的代码:
C++
void add_component(boost::python::object& type)
{
auto constructed_type = type(); // doesn't construct anything!
}
蟒
o = GameObject()
o.add_component(CameraComponent)
我的代码可以很好地执行整个函数,但构造函数永远不会被触发CameraComponent
。
所以我的问题是,给定已知为类型的PyObject*
,我如何构造该类型的实例?
提前非常感谢。
如果boost::python::object
引用类型,则调用它将使用引用的类型构造一个对象:
boost::python::object type = /* Py_TYPE */;
boost::python::object object = type(); // isinstance(object, type) == True
由于Python中的几乎所有内容都是对象,因此接受来自Python的参数作为boost::python::object
将允许任何类型的对象,即使是那些不是类型的对象。 只要对象是可调用的(__call___
),那么代码就会成功。
另一方面,如果要保证提供类型,则一种解决方案是创建一个表示 Python 类型的C++类型,接受它作为参数,并仅在提供 Python 类型时使用自定义转换器构造C++类型。
以下type_object
C++类型表示一个 Python 对象,该对象是一个Py_TYPE
。
/// @brief boost::python::object that refers to a type.
struct type_object:
public boost::python::object
{
/// @brief If the object is a type, then refer to it. Otherwise,
/// refer to the instance's type.
explicit
type_object(boost::python::object object):
boost::python::object(object)
{
if (!PyType_Check(object.ptr()))
{
throw std::invalid_argument("type_object requires a Python type");
}
}
};
...
// Only accepts a Python type.
void add_component(type_object type) { ... }
以下自定义转换器仅在提供Py_TYPE
PyObject*
时构造type_object
实例:
/// @brief Enable automatic conversions to type_object.
struct enable_type_object
{
enable_type_object()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<type_object>());
}
static void* convertible(PyObject* object)
{
return PyType_Check(object) ? object : NULL;
}
static void construct(
PyObject* object,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Obtain a handle to the memory block that the converter has allocated
// for the C++ type.
namespace python = boost::python;
typedef python::converter::rvalue_from_python_storage<type_object>
storage_type;
void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
// Construct the type object within the storage. Object is a borrowed
// reference, so create a handle indicting it is borrowed for proper
// reference counting.
python::handle<> handle(python::borrowed(object));
new (storage) type_object(python::object(handle));
// Set convertible to indicate success.
data->convertible = storage;
}
};
...
BOOST_PYTHON_MODULE(...)
{
enable_type_object(); // register type_object converter.
}
下面是一个完整的示例,演示如何公开一个需要 Python 类型的函数,然后构造该类型的实例:
#include <iostream>
#include <stdexcept> // std::invalid_argument
#include <boost/python.hpp>
/// @brief boost::python::object that refers to a type.
struct type_object:
public boost::python::object
{
/// @brief If the object is a type, then refer to it. Otherwise,
/// refer to the instance's type.
explicit
type_object(boost::python::object object):
boost::python::object(object)
{
if (!PyType_Check(object.ptr()))
{
throw std::invalid_argument("type_object requires a Python type");
}
}
};
/// @brief Enable automatic conversions to type_object.
struct enable_type_object
{
enable_type_object()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<type_object>());
}
static void* convertible(PyObject* object)
{
return PyType_Check(object) ? object : NULL;
}
static void construct(
PyObject* object,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Obtain a handle to the memory block that the converter has allocated
// for the C++ type.
namespace python = boost::python;
typedef python::converter::rvalue_from_python_storage<type_object>
storage_type;
void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
// Construct the type object within the storage. Object is a borrowed
// reference, so create a handle indicting it is borrowed for proper
// reference counting.
python::handle<> handle(python::borrowed(object));
new (storage) type_object(python::object(handle));
// Set convertible to indicate success.
data->convertible = storage;
}
};
// Mock API.
struct GameObject {};
struct CameraComponent
{
CameraComponent()
{
std::cout << "CameraComponent()" << std::endl;
}
};
boost::python::object add_component(GameObject& /* self */, type_object type)
{
auto constructed_type = type();
return constructed_type;
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Enable receiving type_object as arguments.
enable_type_object();
python::class_<GameObject>("GameObject")
.def("add_component", &add_component);
python::class_<CameraComponent>("CameraComponent");
}
交互式用法:
>>> import example
>>> game = example.GameObject()
>>> component = game.add_component(example.CameraComponent)
CameraComponent()
>>> assert(isinstance(component, example.CameraComponent))
>>> try:
... game.add_component(component) # throws Boost.Python.ArgumentError
... assert(False)
... except TypeError:
... assert(True)
...
这实际上总是有效的,但是编译器以某种方式优化了构造函数逻辑,所以我的断点从未被命中!
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 使用C对象指针构建PyObject*
- 如何获取与 SWIG 中的C++对象关联的 *PyObject*
- Python C API - 如何从 PyObject 构造对象
- 将 PyObject* 转换为C++对象