首页 > 解决方案 > 从 C++ 调用 python 函数(Visual Studio 2019)

问题描述

我想从 Visual Studio 2019 的 python 文件中调用该函数。通过谷歌搜索,看起来我需要使用以下函数。我在为 c++ 存储 exe 的同一位置添加了一个“Sample.py”。

int main()
{
    Py_Initialize();
    // Create some Python objects that will later be assigned values.

    PyObject* pName, * pModule, * pFunc, * pArgs = nullptr, * pValue; 
    pName = PyUnicode_FromString((char*)"Sample"); 
    pModule = PyImport_Import(pName); 
    pFunc = PyObject_GetAttrString(pModule, (char*)"fun"); 
    pValue = PyObject_CallObject(pFunc, pArgs);
}

在与 c++ 的 exe 位于同一路径的“Sample.py”中

import matplotlib.pyplot as plt

def fun(): x = [1,2,3]
y = [2,4,1]
plt.plot(1, 2)

当我运行 c++ 代码时,它会在 PyObject_CallObject(pFunc, pArgs); 处引发异常。在 ConsoleApplication9.exe 中的 0x00007FFC54B6F3D2 (python37.dll) 处抛出异常:0xC0000005:访问冲突读取位置 0x0000000000000008。抛出未处理的异常:读取访问冲突。 v是 nullptr。

我只想知道我是否在我的视觉工作室设置中遗漏了任何东西

因为当我将 sample.py 更改为没有#import 的情况下,它工作正常

def fun():  print("Hello from a function")

标签: pythonc++

解决方案


我更改了以下内容,现在绘图可以了!

#include <iostream>
#include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\include\Python.h"

using namespace std;

int main(int)
{
    Py_Initialize();//-Initialize python interpreter
    if (!Py_IsInitialized())
    {
        PyRun_SimpleString("print 'inital error!' ");
        return -1;
    }
    //PyRun_SimpleString("print 'inital ok! ");
    PyRun_SimpleString("import sys");//--It is equivalent to the import sys statement in python, sys is to deal with the interpreter
    PyRun_SimpleString("sys.path.append('./')"); //Specify the directory where pytest.py is located
    PyRun_SimpleString("sys.argv = ['python.py']");
    PyObject* pName = NULL;
    PyObject* pMoudle = NULL;//---Store the python module to be called
    PyObject* pFunc = NULL;//---Store the function to be called
    pName = PyUnicode_FromString("Sample"); //Specify the file name to be imported
    pMoudle = PyImport_Import(pName);//--Using the import file function to import the helloWorld.py function
    if (pMoudle == NULL)
    {
        PyRun_SimpleString("print 'PyImport_Import error!' ");
        return -1;
    }
    pFunc = PyObject_GetAttrString(pMoudle, "fun");//--Find the hello function in the python reference module helloWorld.py
    PyObject_CallObject(pFunc, NULL);//---Call hello function

    Py_Finalize();//---Clean up the python environment and release resources
    return 0;
}

Sample.py 中的绘图脚本是:

import matplotlib.pyplot as plt
import numpy as np
def fun():
    x = np.arange(-5, 5, 0.02)
    y = np.sin(x)
    plt.axis([-np.pi, np.pi, -2, 2])
    plt.plot(x, y, color="r", linestyle="-", linewidth=1)
    plt.show()

推荐阅读