深入浅析深入浅析 C++ 调用调用 Python 模块模块
Python 提供了 C++ 库,使得开发者能很方便地从 C++ 程序中调用 Python 模块。接下来通过本文给大家介绍
C++ 调用 Python 模块的相关知识,需要的朋友参考下吧
一般开发过游戏的都知道Lua和C++可以很好的结合在一起,取长补短,把Lua脚本当成类似动态链接库来使用,很好的利用
了脚本开发的灵活性。而作为一门流行的通用型脚本语言Python,也是可以做到的。在一个C++应用程序中,我们可以用一组
插件来实现一些具有统一接口的功能,一般插件都是使用动态链接库实现,如果插件的变化比较频繁,我们可以使用Python
来代替动态链接库形式的插件(堪称文本形式的动态链接库),这样可以方便地根据需求的变化改写脚本代码,而不是必须重
新编译链接二进制的动态链接库。灵活性大大的提高了。
作为一种胶水语言,Python 能够很容易地调用 C 、 C++ 等语言,也能够通过其他语言调用 Python 的模块。
Python 提供了 C++ 库,使得开发者能很方便地从 C++ 程序中调用 Python 模块。
具体的文档参考官方指南:
Embedding Python in Another Application
调用方法调用方法
1 链接到 Python 调用库
Python 安装目录下已经包含头文件( include 目录)和库文件 ( Windows 下为 python27.lib)。
使用之前需要链接到此库。
2 直接调用 Python 语句
<code class="language-cpp hljs ">#include "python/Python.h"
int main()
{
Py_Initialize(); ## 初始化
PyRun_SimpleString("print 'hello'");
Py_Finalize(); ## 释放资源
}
</code>
3 加载 Python 模块并调用函数
~/test 目录下含有 test.py :
<code class="language-python hljs ">def test_add(a, b):
print 'add ', a, ' and ', b
return a+b</code>
则可以通过以下代码调用 test_add 函数 :
<code class="language-cpp hljs ">#include "python/Python.h"
#include <iostream>
using namespace std;
int main()
{
Py_Initialize(); // 初始化
// 将Python工作路径切换到待调用模块所在目录,一定要保证路径名的正确性
string path = "~/test";
string chdir_cmd = string("sys.path.append(\"") + path + "\")";
const char* cstr_cmd = chdir_cmd.c_str();
PyRun_SimpleString("import sys");
PyRun_SimpleString(cstr_cmd);
// 加载模块
PyObject* moduleName = PyString_FromString("test"); //模块名,不是文件名
PyObject* pModule = PyImport_Import(moduleName);
if (!pModule) // 加载模块失败
{
cout << "[ERROR] Python get module failed." << endl;
return 0;
}
cout << "[INFO] Python get module succeed." << endl;
// 加载函数
PyObject* pv = PyObject_GetAttrString(pModule, "test_add");
if (!pv || !PyCallable_Check(pv)) // 验证是否加载成功
{
cout << "[ERROR] Can't find funftion (test_add)" << endl;
return 0;
}
评论2