Python C API-如何从PyObject构造对象
作者:互联网
我正在寻找一种已知的PyObject *是否存在一种很好的“本机”方式来构建对象.
这是我目前的代码:
C
void add_component(boost::python::object& type)
{
auto constructed_type = type(); // doesn't construct anything!
}
Python
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类型,将其接受为参数,并仅在以下情况下使用自定义转换器构造C类型:提供了Python类型.
以下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) { ... }
以下自定义转换器将仅在为type_object实例提供PyObject *作为Py_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;
}
};
...
BOOST_PYTHON_MODULE(...)
{
enable_type_object(); // register type_object converter.
}
这是一个完整的示例demonstrating,它公开了一个需要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)
...
标签:boost-python,boost,python,c-4 来源: https://codeday.me/bug/20191119/2033886.html