中断在windowsapi中嵌入Python的持久线程

2024-05-14 07:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个简单的Windows API C++代码,允许任意执行Python代码,但是如果执行时间太长(例如,五秒),则中断执行。为简单起见,我当前将包含要执行的代码的字符串传递到函数PyRun_String()。你知道吗

<>这个C++是被编译成.dll的,而我要扩展的我的调用程序不能访问会让python进程或子进程分叉的函数。你知道吗

我被告知TerminateThread()是结束线程的不安全方法,因为它会导致内存泄漏和同步错误。如何在线程中优雅地退出函数PyRun_String()?你知道吗

我的代码如下:

#include "stdafx.h"

DWORD WINAPI pystr(__in LPVOID lpParameter)
{
    // Local Variables
    PyObject *pResult, *pDict, *pMod;
    char *str = (char*) lpParameter;

    // Initialize the Python Interpreter
    Py_Initialize();

    // Initialize the global and local space.
    pMod = PyImport_AddModule("__main__");
    pDict = PyModule_GetDict(pMod);

    // Run the Python String.
    pResult = PyRun_String(str, Py_file_input, pDict, pDict);

    // Exit
    Py_Finalize();
    return 0;
}

char* Run_PyString(char* str)
{
    // Local Variables
    HANDLE handle;
    DWORD  thread_id;

    // Create the Thread and wait for it to return
    handle = CreateThread(0, 0, pystr, (LPVOID) str, 0, &thread_id);
    WaitForSingleObject(handle, INFINITE);

    // Close the Thread Handle
    CloseHandle(handle);
    return "";
}

Tags: the函数代码pystringreturn进程pyrun

热门问题