C++调用pyhton代码(无参)

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!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值