我想用 PyObjects 编写一个 C++ 类,以便从 Python 访问它们,并使用现有的 Python 对象实例引用它们。简而言之,我想在 C++ 类中存储/管理 Python 对象实例。
例如:
struct Var
{
PyObject *Test_1;
PyObject *Test_2;
};
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(Var)
{
class_<Var>("Var", init<std::string>())
.def_readwrite("Test_1", &Var::value)
.def_readwrite("Test_2", &Var::value)
;
}
在 python 中,如果可以使用 Boost.Python,我想这样做:
class Test:
def __init__(self, a = 0, b = 2):
self.a = 0
self.b = 0
test = Test(2,2)
import Var
newStore = Var
newStore.Test_1 = test
预先非常感谢您!
greets
Flo
当使用 Boost.Python 管理 C++ 中的 Python 对象时,应该考虑使用boost::python::object http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/object.html#object-spec类而不是PyObject
. The object
其行为与 Python 变量非常相似,允许在 C++ 中使用类似 Python 的代码。此外,它们的行为类似于智能指针,提供引用计数和生命周期管理,因为人们需要使用PyObject
.
这是一个基于原始代码的完整示例,演示了如何使用boost::python::object
and PyObject
:
#include <boost/python.hpp>
/// @brief Mockup type that can manage two Python objects.
struct var
{
boost::python::object test_1; // managed
PyObject* test_2; // must explicitly manage
var()
: test_2(Py_None)
{
Py_INCREF(test_2);
}
~var()
{
Py_DECREF(test_2);
}
};
/// @brief Auxiliary function used to return a non-borrowed reference to
// self.test_2. This is necessary because Boost.Python assumes
// that PyObject* passed from C++ to Python are not borrowed.
PyObject* var_test_2_getter(const var& self)
{
PyObject* object = self.test_2;
Py_INCREF(object);
return object;
}
/// @brief Auxiliary function used to manage the reference count of
/// objects assigned to var.test_2.
void var_test_2_setter(var& self, PyObject* object)
{
Py_DECREF(self.test_2);
self.test_2 = object;
Py_INCREF(self.test_2);
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<var>("Var", python::init<>())
.def_readwrite("Test_1", &var::test_1)
.add_property("Test_2", &var_test_2_getter, &var_test_2_setter)
;
}
互动使用:
>>> class Test:
... def __init__(self, a=0, b=2):
... self.a = a
... self.b = b
...
>>> test = Test(2, 2)
>>> from sys import getrefcount
>>> count = getrefcount(test)
>>> import example
>>> store = example.Var()
>>> store.Test_1 = test
>>> assert(store.Test_1 is test)
>>> assert(count + 1 == getrefcount(test))
>>> assert(store.Test_1.a == 2)
>>> store.Test_1.a = 42
>>> assert(test.a == 42)
>>> store.Test_2 = test
>>> assert(store.Test_2 is test)
>>> assert(count + 2 == getrefcount(test))
>>> assert(count + 2 == getrefcount(store.Test_2))
>>> store.Test_2 = None
>>> assert(count + 1 == getrefcount(test))
>>> store = None
>>> assert(count == getrefcount(test))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)