gpt4 book ai didi

c++ - SWIG 相当于存储一个 boost::python::object

转载 作者:太空宇宙 更新时间:2023-11-04 12:10:45 25 4
gpt4 key购买 nike

什么是 SWIG 相当于存储任意 python 对象的拷贝?

我很确定我所问的是可能的,因为它可以与 boost::python 一起工作(见下文),但我看不到使用 SWIG 来实现这一点的方法。

#include <boost/python.hpp>

using namespace boost::python;

class MyClass
{
public:
// other operations
object get_info() { return info_; }
void set_info(object info) { info_ = info; }

private:
object info_;
};

BOOST_PYTHON_MODULE( mymodule )
{
class_<MyClass>("MyClass")
.def("get_info", &MyClass::get_info )
.def("set_info", &MyClass::set_info )
;
}

最佳答案

最简单的例子是:

%module test

%inline %{
class MyClass
{
public:
// other operations
PyObject *get_info() { return info_; }
void set_info(PyObject *info) { info_ = info; }

private:
PyObject *info_;
};
%}

例如:

swig -python -Wall -c++ test.ig++ -Wall -Wextra test_wrap.cxx -I/usr/include/python2.6 -o _test.so -sharedpythonPython 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)[GCC 4.4.5] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import test>>> foo = test.MyClass()>>> str = "hi">>> foo.set_info(str)>>> print foo.get_info()hi>>>

But note that in this case the ownership of the object has not been changed. If I'd done foo.set_info("hi") instead then it would have been released because no references were retained by the time it called foo.get_info().

You can fix that by adding a call to:

Py_INCREF(info);

set_info() 中,但是你需要在析构函数中有一个相应的 DECREF,或者如果 set_info() 在引用已经被保存时被调用,或者用于复制构造或分配。 (或者一些不错的 RAII 类型来为你做这一切......)

关于c++ - SWIG 相当于存储一个 boost::python::object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9969347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com