我有这个 Visual C++ 代码,加上嵌入的 Python,当我尝试使用以下代码运行外部 Python 代码时,我在调试模式下收到错误:
Unhandled exception at 0x77cf15de in CMLAir.exe (my code):
access violation writing location 0x00000014.
当 PyRun_File 函数通过 c++ 代码调用时,就会发生错误。
这是 C++ 函数:
void CRailtestDoc::OnPreprocessorRunscript()
{
#ifdef USE_PYTHON
//for now, pull up Open dialog for user to specify script
CString strPythonScriptPath;
CString strTitle = "Run Python Script";
CFileDialog dlg(TRUE, ".py", NULL);
dlg.m_ofn.Flags |= OFN_PATHMUSTEXIST;
dlg.m_ofn.lpstrTitle = (LPCTSTR)strTitle;
if (dlg.DoModal() == IDOK)
{
strPythonScriptPath = dlg.GetFileName( );
}
else
{
return;
}
FILE* fp;
fp = fopen((LPCSTR)strPythonScriptPath, "r+");
if (fp == NULL)
{
CString strErrMsg;
strErrMsg.Format("troble opening python file: %s", (LPCSTR)strPythonScriptPath);
AfxMessageBox(strErrMsg);
return;
}
//
// TODO: we need to make sure that we don't call Py_Initialize more than once
// see Python/C API Reference Manual section 1.4
//
m_bRunningScript = TRUE;
Py_Initialize();
PycString_IMPORT; //Macro for importing cStringIO objects
//start up our own modules? Is this needed here?
initcml();
initresults();
PyObject* localDict;
PyObject* mainModule;
PyObject* mainModuleDict;
mainModule = PyImport_AddModule("__main__");
//mainModule = PyImport_AddModule("__builtins__");
if(mainModule==NULL)
{
AfxMessageBox("Problems running script");
m_bRunningScript = FALSE;
return;
}
mainModuleDict = PyModule_GetDict(mainModule);
localDict = PyDict_New();
//Now run the selected script
PyObject* tempPyResult =
PyRun_File(fp, strPythonScriptPath, Py_file_input, mainModuleDict, mainModuleDict);
//<=== where the code exit with unhandled exception at 0x77cf15de
UNREFERENCED_PARAMETER(tempPyResult);
// See if an exception was raised and not handled.
// If so, return traceback to user as MsgBox
}
这是我试图从 C++ 代码运行的外部 Python 脚本:
import cml, results
def main():
baseCase = "C:\\Program Files\\CMLAir32\\Examples\\Quick4_Example.cml"
outFile = "c:\\output.txt"
f = open(outFile, "w")
#open our .cml case
if cml.OpenCase(baseCase) == 0:
return
#set initial mesh size
meshSize = 177
cml.SetGridSizeX(meshSize)
cml.SetGridSizeY(meshSize)
cml.SaveCaseNoWarn()
while meshSize < 400:
#run it
cml.RunCaseNoWarn()
#get results
res = results.Results()
res.GetResults()
if res.HasResults() == 0:
cml.MsgBox("error getting results, aborting")
return
#pull out minimum fly height
singleResult = res[0]
fh = singleResult.minFH
#output current mesh size and minimum fly height
dataStr = str(meshSize) + ' ' + str(fh)
f.write(dataStr)
#increment mesh size
meshSize += 16
cml.SetGridSizeX(meshSize)
cml.SetGridSizeY(meshSize)
cml.SaveCaseNoWarn()
main()
为什么 PyRun_File 函数会报错?
我对在 C++ 代码中嵌入 Python 了解不多,所以我非常感谢这里的一些指针。请记住,我对 Python 还比较陌生。我的大部分编程经验都在 Visual C++ 中。在这种情况下,将两者结合在一起的最佳方法是什么?