调用Py_Initialize时防止程序崩溃

时间:2016-06-29 11:00:56

标签: python c++ error-handling crash

我要在一些独立的应用程序中嵌入python,所以我有代码:

#include <Python.h>

wchar_t* AssemblyName = NULL;

bool InitPython()
{
    Py_SetPath(L".\\Lib;.\\Lib.zip");

    if (AssemblyName == NULL && (AssemblyName = Py_DecodeLocale("My.Python.dll", NULL)) == NULL)
        return false;

    Py_SetProgramName(AssemblyName);
    Py_Initialize();

    return true;
}

void ReleasePython()
{
    if (AssemblyName != NULL)
    {
        Py_Finalize();
        PyMem_RawFree(AssemblyName);
        AssemblyName = NULL;
    }
}

int main(int argc, char *argv[])
{
    InitPython();
    PyRun_SimpleString("from time import time,ctime\nprint('Today is', ctime(time()))\n");
    ReleasePython();
    return 0;
}

请注意,我正在使用python库的相对路径。所以问题是如果文件夹中没有这样的路径 - 程序将崩溃而不是以某种方式将错误返回给调用者。有没有办法挂钩python错误处理?

0 个答案:

没有答案
相关问题