Boost Python学习笔记(五)

时间:2022-12-27 09:44:07

你将学到什么

  • 在C++中调用Python代码时的返回值问题

基础类型

修改Python脚本(build/zoo.py)

def rint():
    return 2

def rstr():
    return "fwd"

if __name__ == '__main__':
    pass

修改源文件(main.cpp)

#include <iostream>
#include <boost/python.hpp>

using namespace boost::python;
using namespace boost::python::detail;

int main()
{
  Py_Initialize();
  if (!Py_IsInitialized())
  {
    std::cout << "Initialize failed" << std::endl;
    return -1;
  }

  try
  {
    object sys_module = import("sys");
    str module_directory(".");
    sys_module.attr("path").attr("insert")(1, module_directory);
    object module = import("zoo");
    object x = module.attr("rint")();
    int rx = extract<int>(x);
    std::cout << "rint: " << rx << std::endl;
    object y = module.attr("rstr")();
    std::string rs = extract<std::string>(y);
    std::cout << "rstr: " << rs << std::endl;
  }
  catch (const error_already_set&)
  {
    PyErr_Print();
  }
  Py_Finalize();
  return 0;
}

标准库

修改Python脚本(build/zoo.py)

def rvec():
    return [1, 2, 3, "fwd"]

if __name__ == '__main__':
    pass

修改源文件(main.cpp)

#include <iostream>
#include <vector>
#include <string>
#include <boost/python.hpp>

using namespace boost::python;
using namespace boost::python::detail;

int main()
{
  Py_Initialize();
  if (!Py_IsInitialized())
  {
    std::cout << "Initialize failed" << std::endl;
    return -1;
  }

  try
  {
    object sys_module = import("sys");
    str module_directory(".");
    sys_module.attr("path").attr("insert")(1, module_directory);
    object module = import("zoo");
    object v = module.attr("rvec")();
    boost::python::handle<> v_iter(PyObject_GetIter(v.ptr()));
    std::cout << "rvec: ";
    while (true)
    {
      handle<> py_hdl(allow_null(PyIter_Next(v_iter.get())));
      if (PyErr_Occurred())
        throw_error_already_set();
      if (!py_hdl.get())
        break;
      object py_obj(py_hdl);
      object r = py_obj.attr("__str__")();
      std::string rs = extract<std::string>(r);
      std::cout << rs << " ";
    }
    std::cout << std::endl;
  }
  catch (const error_already_set&)
  {
    PyErr_Print();
  }
  Py_Finalize();
  return 0;
}