C++调用python代码(无参)
文件夹结构
|--c_python
|--hello.py
|--main.cpp
建立python代码
在c_python文件夹内新建python代码hello.py,代码内容:
def hi():
print("hello world!")
return
def main():
hi()
return
if __name__ == "__main__":
main()
运行python代码,结果输出 hello world!
建立C++代码
在c_python文件夹内新建c++代码main.cpp,代码内容:
#include <Python.h>
#include <iostream>
int main()
{
// 1. 初始化python接口
Py_Initialize(); //初始化
if (!Py_IsInitialized())
{
std::cout << "python init failed" << std::endl;
return 1;
}
// 2. 初始化python系统文件路径,保证可以访问到.py文件
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')"); //要将python代码根目录添加到路径中
// 3. 调用python文件名,不用谢后缀
PyObject* module = PyImport_ImportModule("hello");
if (module == nullptr)
{
std::cout << "module not found: hello.py" << std::endl;
return 1;
}
// 4. 获取函数对象
PyObject* func = PyObject_GetAttrString(module, "hi");
if (!func || !PyCallable_Check(func))
{
std::cout << "function not found: hi" << std::endl;
return 1;
}
// 5. 调用函数
PyObject_CallObject(func, nullptr);
//6. 结束python接口初始化
Py_Finalize();
return 0;
}
运行C++代码
这里在ubuntu环境下,使用g++方式运行(python改成自己电脑安装对应的版本)
g++ main.cpp -o hello -I/usr/include/python3.10 -lpython3.10
./hello
结果输出: hello world!