【问题标题】:embeding extended python eats all the memory嵌入扩展 python 吃掉所有内存
【发布时间】:2014-06-08 21:33:20
【问题描述】:

在关注pythonembedding/extending tutorial时,我想出了以下代码

#include <boost/filesystem.hpp>
#include <Python.h>
static PyObject *
spam_system(PyObject *self, PyObject *args) {
    const char *command;
    int sts;
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
}
static char SpamModuleName[] = "spam\000";
int main(int argc, char const *argv[]) {
    Py_SetPath((
        boost::filesystem::canonical("./python_lib.zip").wstring()
    ).c_str());
    PyImport_AppendInittab(SpamModuleName,[](){
        static PyMethodDef SpamMethods[] = {
            {"system", spam_system, METH_VARARGS, "Execute a shell command."},
            {NULL, NULL, 0, NULL}
        };
        static struct PyModuleDef spammodule = {
            PyModuleDef_HEAD_INIT,
            SpamModuleName,
            NULL,
            -1,
            SpamMethods,
            NULL, NULL, NULL, NULL
        };
        return PyModule_Create(&spammodule);
    });
    Py_Initialize();
    PyRun_SimpleString(
        "import spam\n"
        "status = spam.system(\"ls -l\")\n"
    );
    Py_Finalize();
    return 0;
}

代码编译良好(使用 g++ -std=c++11 main.cpp -lpython33.64 -lboost_filesystem -lboost_system -s 我使用 x64 native mingw toolchain by Stephan T. Lavavej)但是在运行我的程序时分配了大约 4 gig 的 ram 并且在 (procexp screenshot)PyRun_SimpleString("import spam\n") 中有 100% 的 cpu 使用率比经常崩溃的蟒蛇MemoryError

PyImport_ImportModule(SpamModuleName); 也使程序崩溃,在分配大量内存之后也是如此(事实上我从未成功运行过此函数)。

如果我结束所有其他程序并尽可能多地释放内存,则程序运行良好并产生预期的输出,但资源消耗使其无法使用。我在做什么错/是什么让 python 使用了这么多资源?

编辑在对 mingw-w64 irc 进行讨论后,我得到了它的工作,并将发布解决方案作为答案,以防其他人发现自己在我的位置

【问题讨论】:

标签: python c++ mingw-w64


【解决方案1】:

感谢用户alexeyktietz 的广泛帮助,我指出使用64 位VC 构建的python.dll 在导入由GCC 构建的x64 二进制文件时存在问题。解决方案是自己构建库,同时修补它以在 MINGWx64 下编译。

可以找到those patches hereprebuilt libraries here

【讨论】:

猜你喜欢
  • 2021-03-24
  • 1970-01-01
  • 2011-07-12
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多