python - 嵌入扩展的 python 会占用所有内存

标签 python c++ mingw-w64

跟随 python embedding/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 我使用 Stephan T. Lavavej 的 x64 native mingw toolchain)当运行我的程序时,我分配了大约 4 gig 的 ram 并且有 100% 的 cpu 使用率 (procexp screenshot)PyRun_SimpleString("import spam\n") 中并且经常因 pythons MemoryError 而崩溃。

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

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

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

最佳答案

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

可以找到those patches hereprebuilt libraries here .

关于python - 嵌入扩展的 python 会占用所有内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24062286/

相关文章:

c++ - MinGW64 和 "conflicting declaration of C function int select(...)"

python - 词频硬件

python - 安装 bsddb 包 - python

c++ - 用于求解具有三对角矩阵的线性方程组的库?

c++ - 在 std::unordered_map 中使用模板化键

c++ - 尝试在 C++、MinGW 上获取当前进程内存大小时出错

c++ - std::max_align_t 无法打印其值

python - 在 Django 的 ORM 中使用带有 UPDATE 的子查询

python - 如何遍历所有字典组合

c++ - qt linux "QMAKE_CXXFLAGS += -std=c++11"相当于 windows?