首页 > 编程语言 >c++ 调用 python 备忘

c++ 调用 python 备忘

时间:2022-11-18 16:36:48浏览次数:39  
标签:pFile python ob c++ 备忘 char base size pBytes

PyBytesObject 值的获取:

    PyObject *pFuncSetCredentialResult = PyObject_CallObject(pFuncSetCredential, pFuncSetCredentialArgs);
        PyBytesObject* pBytes = (PyBytesObject*)pFuncSetCredentialResult;
        char* data = new char[pBytes->ob_base.ob_size + 1];
        memcpy(data, pBytes->ob_sval, pBytes->ob_base.ob_size);
        FILE * pFile = fopen("C:\\xxxx\\myfile.tif", "wb");
        fwrite(data, sizeof(char), pBytes->ob_base.ob_size, pFile);
        fclose(pFile);

通过值构造新的 PyBytesObject:

FILE* f = fopen("C:\\xxx\\myfile.tif", "rb");
    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    rewind(f);
    unsigned char* data = new unsigned char[size];
    fread(data, sizeof(char), size, f);
    fclose(f);

    PyBytesObject* pBytes = (PyBytesObject*)PyBytes_FromStringAndSize((const char*)data, (Py_ssize_t)size);
    char* data2 = new char[pBytes->ob_base.ob_size + 1];
    memcpy(data2, pBytes->ob_sval, pBytes->ob_base.ob_size);
    FILE * pFile = fopen("C:\\xxx\\myfile2.tif", "wb");
    fwrite(data2, sizeof(char), pBytes->ob_base.ob_size, pFile);
    fclose(pFile);

 其它示例:

void runPythonScriptDemo()
{
    cout << "started" << endl;

    if (!Py_IsInitialized())
        Py_Initialize();

    if (!Py_IsInitialized())
    {
        cout << "Py_IsInitialized failed" << endl;
        return;
    }

    cout << "Py_Initialized !" << endl;

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.insert(0, 'C:/xxx/build')");
    PyRun_SimpleString("import main");
    PyRun_SimpleString("main.msgbox('python from c++')");

    Py_Finalize();
}

void runPythonModuleMethodDemo()
{
    cout << "started" << endl;

    if (!Py_IsInitialized())
        Py_Initialize();

    if (!Py_IsInitialized())
    {
        cout << "Py_IsInitialized failed" << endl;
        return;
    }

    cout << "Py_Initialized !" << endl;

    //设置路径起作用,说明脚本执行与动态调用在一个执行上下文
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.insert(0, 'C:/xxxx/build')");

    //从当前目录下获取模块
    PyObject *pModule = PyImport_ImportModule("main");

    //获取模块的字典,所有方法存在于字典中
    PyObject *pDict = PyModule_GetDict(pModule);

    //通知系统尽快回收pModule
    Py_DECREF(pModule);

    //从方法字典中查找方法
    PyObject *pFunc = PyDict_GetItemString(pDict, "msgbox");
    if (!pFunc || !PyCallable_Check(pFunc))
    {
        cout << "load function 'msgbox' failed" << endl;
        Py_Finalize();
        return;
    }

    //构建字符串输入参数
    PyObject *str = Py_BuildValue("s", "hello");

    PyObject *pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, str);

    try
    {
        PyObject *pResult = PyObject_CallObject(pFunc, pArgs);
    }
    catch (const std::exception ex)
    {
        printf("call function error: %s", ex.what());
        Py_Finalize();
        return;
    }

    Py_Finalize();
}

void runCythonCppDemo()
{
    cout << "started" << endl;

    if (!Py_IsInitialized())
        Py_Initialize();

    if (!Py_IsInitialized())
    {
        cout << "Py_IsInitialized failed" << endl;
        return;
    }

    cout << "Py_Initialized !" << endl;

    PyRun_SimpleString("import os");
    PyRun_SimpleString("os.chdir('C:/xxx/build')");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.insert(0, 'C:/xxx/build')");

    setEncodeKey(123);

    PyRun_SimpleString("import main");
    PyRun_SimpleString("main.showEncodeKey()");

    Py_Finalize();
}

void runRecognizeMainTestDemo()
{
    cout << "started" << endl;

    if (!Py_IsInitialized())
        Py_Initialize();

    if (!Py_IsInitialized())
    {
        cout << "Py_IsInitialized failed" << endl;
        return;
    }

    cout << "Py_Initialized !" << endl;

    //设置路径起作用,说明脚本执行与动态调用在一个执行上下文
    PyRun_SimpleString("import os");
    PyRun_SimpleString("os.chdir('C:/xxx/build')");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.insert(0, 'C:/xxx/build')");

    //从当前目录下获取模块
    PyObject *pModule = PyImport_ImportModule("main");
    if (!pModule || pModule == NULL)
    {
        cout << "import module 'main' failed" << endl;
        Py_Finalize();
        return;
    }

    //获取模块的字典,所有方法存在于字典中
    PyObject *pDict = PyModule_GetDict(pModule);

    //通知系统尽快回收pModule
    Py_DECREF(pModule);

    //从方法字典中查找方法
    PyObject *pFunc = PyDict_GetItemString(pDict, "test");
    if (!pFunc || !PyCallable_Check(pFunc))
    {
        cout << "load function 'test' failed" << endl;
        Py_Finalize();
        return;
    }

    //无参构造
    PyObject *pArgs = PyTuple_New(0);

    try
    {
        PyObject *pResult = PyObject_CallObject(pFunc, pArgs);
    }
    catch (const std::exception ex)
    {
        printf("call function error: %s", ex.what());
        Py_Finalize();
        return;
    }

    Py_Finalize();
}

void runRecognizeReadFileTest()
{
    cout << "started" << endl;

    if (!Py_IsInitialized())
        Py_Initialize();

    if (!Py_IsInitialized())
    {
        cout << "Py_IsInitialized failed" << endl;
        return;
    }

    cout << "Py_Initialized !" << endl;

    //设置路径起作用,说明脚本执行与动态调用在一个执行上下文
    PyRun_SimpleString("import os");
    PyRun_SimpleString("os.chdir('C:/xxx/build')");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.insert(0, 'C:/xxx/build')");

    //从当前目录下获取模块
    PyObject *pModule = PyImport_ImportModule("func_interface");
    if (!pModule || pModule == NULL)
    {
        cout << "import module 'func_interface' failed" << endl;
        Py_Finalize();
        return;
    }

    //获取模块的字典,所有方法存在于字典中
    PyObject *pDict = PyModule_GetDict(pModule);

    //通知系统尽快回收pModule
    Py_DECREF(pModule);

    //从方法字典中查找方法
    PyObject *pFunc = PyDict_GetItemString(pDict, "read_file");
    if (!pFunc || !PyCallable_Check(pFunc))
    {
        cout << "load function 'read_file' failed" << endl;
        Py_Finalize();
        return;
    }

    //入参构造
    PyObject *pArgs = PyTuple_New(1);
    PyObject *str = Py_BuildValue("s", "./images/00000009-cdbeefd1e5bc-4449-bc58-9d36975c288601.tif");
    PyTuple_SetItem(pArgs, 0, str);

    try
    {
        //接收python返回的byte数组
        PyObject *pResult = PyObject_CallObject(pFunc, pArgs);
        PyBytesObject* pBytes = (PyBytesObject*)pResult;
        char* data = new char[pBytes->ob_base.ob_size + 1];
        memcpy(data, pBytes->ob_sval, pBytes->ob_base.ob_size);
        FILE * pFile = fopen("C:\\Users\\Knife\\Desktop\\myfile.tif", "wb");
        fwrite(data, sizeof(char), pBytes->ob_base.ob_size, pFile);
        fclose(pFile);
        cout << "ok" << endl;
    }
    catch (const std::exception ex)
    {
        printf("call function 'read_file' error: %s", ex.what());
        Py_Finalize();
        return;
    }

    Py_Finalize();
}

 

标签:pFile,python,ob,c++,备忘,char,base,size,pBytes
From: https://www.cnblogs.com/nanfei/p/16903652.html

相关文章

  • python采集信息到prometheus
    采集脚本#coding=utf-8fromprometheus_clientimportGauge,start_http_serverimportrequestsimporttimejvsn=Gauge('zhibiao1','描述',['app_name','app_user'])......
  • python上传maven私仓
    私仓地址:http://nexus.xxxprivate.com/#browse/search/pypi1、绑定我们的私仓地址pipinstallflask-ihttp://nexus.xxxprivate.com/repository/pypi/simple地址如下图,末......
  • python获取pdf文本
     1.pdf文件获取文本importpdfplumberwithpdfplumber.open("4.pdf")aspdf:first_page=pdf.pages[0]print(first_page.chars[0])#获取pdf信息......
  • Python 新环境常见问题
    Troubleshootingwhenrunpythonscriptinnewenvironment 1.Error:pluggy._manager.PluginValidationError:unknownhook'pytest_html_report_title' Resuolt......
  • python-飞机大战1-项目实战
    目标强化面向对象程序设计体验使用​​pygame​​模块进行游戏开发实战步骤​​pygame​​快速体验飞机大战实战确认模块——pygame​​pygame​​就是一个Pytho......
  • python-飞机大战2.游戏框架搭建-项目实战
    目标——使用面相对象设计飞机大战游戏类目标明确主程序职责实现主程序类准备游戏精灵组01.明确主程序职责回顾快速入门案例,一个游戏主程序的职责可以分为两个部分......
  • python-飞机大战3.游戏背景-项目实战
    目标背景交替滚动的思路确定显示游戏背景01.背景交替滚动的思路确定运行备课代码,观察背景图像的显示效果:游戏启动后,背景图像会连续不断地向下方移动在视觉上产生英......
  • python-飞机大战.pygame快速入门-项目实战
    目标项目准备使用​​pygame​​创建图形窗口理解图像并实现图像绘制理解游戏循环和游戏时钟理解精灵和精灵组项目准备新建飞机大战项目新建一个​​hm_01_pyg......
  • 【c&c++】C语言 结构体 - 字节对齐 使用预处理命令 #pragma 对齐
    在C语言中每个数据类型都有他的对齐方式例如char是一个一节对齐,int是四个字节对齐,float是八个字节对齐,short是两个字节对齐由于对齐方式的特性就会拥有相同成员的结......
  • Python PDF文件怎么转换成Word?
    一、演示PythonPDF转Word演示效果(文件比较大处理比较慢): 二、源代码#!/usr/bin/python#-*-coding:UTF-8-*-"""@author:HUI@file:test.py@time:2022/11/......