我在Windows中使用线程将c++编写的插件连接到python脚本。线程将在会话期间被多次调用
问题:
如果我在_beginthread
中传递ArgList
,则在0x1E114A68(python27.dll)处发生错误“未处理的异常xxx.exe文件:0xc000005:读取位置0xFFFFFFFE时发生访问冲突。“,我想这是因为我在Windows开发人员中心的CreatingThreads中读取的:
“请注意,如果要在工作线程终止之前关闭它的句柄,则不会终止该工作线程。但是,句柄将不可用于后续函数调用。“
关于这个错误的起源,我说得对吗?我该如何度过这个难关?在
代码:
我用NULL
作为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();
};
我从主线程(在工作线程完成之前关闭)调用它的方法:
^{2}$注:问题1与此相关的是here
所以,我终于找到了问题所在。希望这能帮助那些有同样问题的人
我仍然不完全理解这是如何工作的,但我基本上需要使用c++中的
new
(以及c中的malloc
)在堆上动态分配内存。有关此here的详细信息在我的情况下,我需要这样做:
然后在主线上:
^{pr2}$我仍然需要更好地理解这一点,还需要学习如何在结尾使用
delete
取消分配,但我的方法是正确的。在注意:我仍然需要与此相关的Question1帮助,所以请看一下。在
相关问题 更多 >
编程相关推荐