簡體   English   中英

如何從C ++返回Python類型的實例

[英]How to return instance of Python's type from C++

如何使用Boost Python函數在C ++中進行定義,Boost Python函數在功能上等效於Python函數

def test():
    return list

盡管Boost.Python TypeWrappers提供了一種方便的方法來為某些內置Python類型實例化對象,但是Boost.Python並未直接提供對一流對象的支持。 但是,可以通過Python / C API中的相應PyTypeObject對象通過Boost.Python返回一流的對象。

在這種情況下,Python / C API中的Python list類型為PyList_Type Python代碼:

def test():
    return list

等效於以下C ++ Boost.Python代碼:

boost::python::object test()
{
  namespace python = boost::python;
  python::handle<PyTypeObject> handle(python::borrowed(&PyList_Type));
  return python::object(handle);
}

(layout-compatible) type, such as PyTypeObject . 當混合了Python / C API和更高級別的Boost.Python代碼,必須使用一個boost::python::handle來構造一個boost::python::object從一個PyObject對象或對象具有 (於版圖兼容)類型,例如PyTypeObject handle本質上是一個負責處理Python參考計數的智能指針。 handle的析構函數將始終減少關聯的Python對象的引用計數。 因此,在構造handle時必須格外小心,因為必須知道該handle是否需要增加引用計數,或者是否已經增加了引用計數。 如果引用計數尚未增加,例如上面的代碼,則必須傳遞boost::python::borrowed()的返回類型來handle的構造函數。 有關更多詳細信息,請考慮閱讀此鏈接


這是一個完整的示例:

#include <boost/python.hpp>

boost::python::object test()
{
  namespace python = boost::python;
  python::handle<PyTypeObject> handle(python::borrowed(&PyList_Type));
  return python::object(handle);
}

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::def("test", &test);
}

互動用法:

>>> import example
>>> assert(example.test() is list)
>>> t = example.test()
>>> assert(t((1, 2, 3)) == [1, 2, 3])
>>> assert(t((1, 2, 3)) != (1, 2, 3))
>>> del t
>>> from sys import getrefcount # test for proper reference counting
>>> n = getrefcount(list)
>>> t = example.test()
>>> assert(n + 1 == getrefcount(list))
>>> del t
>>> assert(n == getrefcount(list))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM