我正在 Windows 中使用线程将 C++ 制作的插件连接到 python 脚本。该线程在会话期间将被多次调用
问题:
如果我通过了ArgList
in the _beginthread
错误“xxx.exe 中 0x1E114A68 (python27.dll) 处出现未处理的异常:0xC0000005:读取位置 0xFFFFFFFE 时发生访问冲突。”被提出,我想这是因为我读到的创建线程 http://msdn.microsoft.com/en-us/library/windows/desktop/ms682516%28v=vs.85%29.aspxWindows 开发中心:
“请注意,如果您要在工作线程终止之前关闭其句柄,则这不会终止工作线程。但是,该句柄将无法在后续函数调用中使用。”
我对这个错误的起源正确吗?我该如何克服这个问题?
Code:
我打了电话_beginthread
with NULL
as the ArgList
并定义了ArgList
在工作线程内部只是为了让线程工作。这是工作线程的代码:
注意:我在调试时注意到_endthread()
未达到。这正常吗?
void py_embed (void*data){
char *argv[4]={"PythonPlugIn2","bridge","test_callsign","MAH543"};
int argc=4;
ofstream textfile3;
textfile3.open("FP_python_embed.txt");
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
PyThreadState *mainThreadState,*myThreadState,*tempState;
PyInterpreterState *mainInterpreterState;
//To inform the interpreter about paths to Python run-time libraries
Py_SetProgramName(argv[0]);
// Initialize the Python Interpreter
Py_Initialize();
// Initialize thread support
PyEval_InitThreads();
// Save a pointer to the main PyThreadState object
mainThreadState = PyThreadState_Get();
// Get a reference to the PyInterpreterState
mainInterpreterState = mainThreadState->interp;
// Create a thread state object for this thread
myThreadState = PyThreadState_New(mainInterpreterState);
// Release global lock
PyEval_ReleaseLock();
// Acquire global lock
PyEval_AcquireLock();
// Swap in my thread state
tempState = PyThreadState_Swap(myThreadState);
// Build the name object
pName = PyString_FromString(argv[1]);
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, argv[2]);
//Do the Python things
PyObject *pArgs2, *pValue2;
pArgs2=Py_BuildValue("(s)",argv[3]);
pValue2 = PyObject_CallObject(pFunc, pArgs2);
textfile3<<PyInt_AsLong(pValue2)<<endl<<" worked1";
textfile3.close();
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Swap out the current thread
PyThreadState_Swap(tempState);
// Release global lock
PyEval_ReleaseLock();
// Clean up thread state
PyThreadState_Clear(myThreadState);
PyThreadState_Delete(myThreadState);
// Finish the Python Interpreter
Py_Finalize();
_endthread();
};
我如何从主线程调用它(在工作线程完成之前关闭):
handle=(HANDLE) _beginthread(py_embed,0,NULL);
注意:与此相关的问题 1 是here https://stackoverflow.com/questions/22413706/thread-running-the-second-time-gives-error