从 C++ 调用 python 脚本,无需每次加载文件

Orf*_*fby 3 c++ python python-embedding

我有一个 python 脚本,我需要调用很多次(大约 160000 次),虽然我可以使用硬 C++ 代码在不到一秒的时间内完成此操作,但如果我尝试加载并调用 python 脚本来执行此操作,它将可能需要几个小时!我认为如果我加载脚本一次,然后一遍又一遍地运行加载的脚本,速度会明显加快。不幸的是,我不知道该怎么做。我认为我无法使用 加载文件ifstream,然后PyRun_SimpleString在字符串的所有行上使用。但是,如果速度不快,是否可以在 python 中返回一个 2D 数组,然后将该数组转换为std::vector

nas*_*-sh 5

考虑以下函数,在一个名为multiply.py

#!/usr/bin/python3

def do_multiply(a, b):
    c = 0
    for i in range(0, a):
        c += b
    return c
Run Code Online (Sandbox Code Playgroud)

在您的 C++ 文件中:

// Load the function 
PyObject *pName     = PyUnicode_FromString("multiply");
PyObject *pModule   = PyImport_Import(pName);
PyObject *pFunction = PyObject_GetAttrString(pModule, "do_multiply")
Run Code Online (Sandbox Code Playgroud)

假设您要调用此函数 3 次,如下所示:

struct NumberPair 
{ 
    int x;
    int y;
};

std::vector<NumberPair> numberPairs { {1, 2}, {5, 6}, {10, 12} };
Run Code Online (Sandbox Code Playgroud)

然后,您可以PyObject_CallFunction在加载模块时简单地调用几次:

for(const auto &numberPair : numberPairs)
{
    PyObject *product = PyObject_CallFunction(pFunction, "ii", numberPair.x, numberPair.y);
    if(product != NULL)
    {
        std::cout << "Product is " << PyLong_AsLong(product) << '\n';
        Py_DECREF(product);
    }
}
Run Code Online (Sandbox Code Playgroud)

无需在调用之间关闭模块PyObject_CallFunction,因此这应该不是问题。