在 C++ 基础知识中使用 Python

using python in c++ basics

本文关键字:Python C++ 基础知识      更新时间:2023-10-16

谁能给我看一个在C ++程序中包含Python的基本程序? 我已经#include <Python.h>工作了,但仅此而已。 如何创建一个字符串,int,并包含一个不属于 Python 库的模块?

也许主要的Python文档可以在这里提供帮助:http://docs.python.org/extending/

这是一个用 C 编写的简单模块: http://docs.python.org/extending/extending.html#a-simple-example

我建议使用Boost Python,因为你使用的是C++而不是C。 文档不错,但请注意,如果您的平台已经为其构建了 Boost 包,则可以跳过"Hello World"示例的大部分内容(因此您无需使用 bjam 自己构建 Boost)。

一定要使用Boost Python。它是一个轻量级依赖项(不需要更改现有的C++代码),尽管它确实略微增加了编译时间。

你可以在 ubuntu 上安装 boost python(或你平台的 pkg 管理器):

$ sudo apt-get install boost-python

那么一个简单的库看起来像这样:

#include <boost/python.hpp>
using namespace boost::python;
struct mystruct {
    int value;
}
int myfunction(int i) {
    return i + 1;
}
BOOST_PYTHON_MODULE(mymodule) {
    // Code placed here will be executed when you do "import mymodule" in python
    initialize_my_module();
    // Declare my C++ data structures
    class_<mystruct>("mystruct")
        .def_readwrite("value", &mystruct::value)
        ;
    // Declare my C++ functions
    def("myfunction", myfunction);
}

然后编译

$ g++ -shared mymodule.cpp -I/usr/include/python -lboost_python -omymodule.so

最后,导入并在python中使用它

>>> import mymodule
>>> mymodule.myfunction(5)
6
>>> s = mymodule.mystruct()
>>> s.value = 4
>>> s.value
4