• Boost Python学习笔记(五)


    你将学到什么

    • 在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;
    }
    
  • 相关阅读:
    Git库搭建好之后,当要提交一个新的文件,需要做的是3个步骤
    实习生面试经历
    Word2007中插入公式之后,公式上下有很大的空白
    参考文献规范格式
    Git学习笔记四--远程仓库
    Git学习笔记三--管理修改、撤销修改、删除文件
    Git学习笔记二--工作区和暂存区
    Git学习笔记一--创建版本库、添加文件、提交文件等
    Errors running builder 'DeploymentBuilder' on project '工程名'
    java中运算符与表达式
  • 原文地址:https://www.cnblogs.com/silvermagic/p/9087514.html
Copyright © 2020-2023  润新知