gpt4 book ai didi

python - 如何通过 Boost.Python 从 python 文件导入函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:21 25 4
gpt4 key购买 nike

我是 boost.python 的新手。看了很多推荐使用 boost.python 来应用 python 的,但是还是不太容易理解和找到适合我的解决方案。

我想要的是直接从python“SourceFile”导入一个函数或类

示例文件: main.cpp 我的Python类.py

假设“MyPythonClass.py”中有一个带有“bark()”函数的“Dog”类,我如何在 cpp 中获取回调和发送参数?

我不知道我该怎么办!请帮助我!

最佳答案

当需要从 C++ 调用 Python,而 C++ 拥有 main 函数时,则必须在 C++ 程序中嵌入 Python 中断程序。 Boost.Python API 并不是 Python/C API 的完整包装器,因此您可能会发现需要直接调用部分 Python/C API。尽管如此,Boost.Python 的 API 可以使互操作性更容易。考虑阅读官方 Boost.Python embedding tutorial获取更多信息。


这是嵌入 Python 的 C++ 程序的基本框架:

int main()
{
// Initialize Python.
Py_Initialize();

namespace python = boost::python;
try
{
... Boost.Python calls ...
}
catch (const python::error_already_set&)
{
PyErr_Print();
return 1;
}

// Do not call Py_Finalize() with Boost.Python.
}

嵌入 Python 时,可能需要扩充 module search path通过PYTHONPATH以便可以从自定义位置导入模块。

// Allow Python to load modules from the current directory.
setenv("PYTHONPATH", ".", 1);
// Initialize Python.
Py_Initialize();

通常,Boost.Python API 提供了一种以类似 Python 的方式编写 C++ 代码的方法。下面的例子demonstrates在 C++ 中嵌入 Python 解释器,并让 C++ 从磁盘导入 MyPythonClass Python 模块,实例化 MyPythonClass.Dog 实例,然后调用 bark()Dog 实例上:

#include <boost/python.hpp>
#include <cstdlib> // setenv

int main()
{
// Allow Python to load modules from the current directory.
setenv("PYTHONPATH", ".", 1);
// Initialize Python.
Py_Initialize();

namespace python = boost::python;
try
{
// >>> import MyPythonClass
python::object my_python_class_module = python::import("MyPythonClass");

// >>> dog = MyPythonClass.Dog()
python::object dog = my_python_class_module.attr("Dog")();

// >>> dog.bark("woof");
dog.attr("bark")("woof");
}
catch (const python::error_already_set&)
{
PyErr_Print();
return 1;
}

// Do not call Py_Finalize() with Boost.Python.
}

给定一个包含以下内容的 MyPythonClass 模块:

class Dog():
def bark(self, message):
print "The dog barks: {}".format(message)

以上程序输出:

The dog barks: woof

关于python - 如何通过 Boost.Python 从 python 文件导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620134/

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