从Visual C ++代码运行Python(嵌入式Python)

时间:2012-06-15 18:40:03

标签: python visual-c++ python-c-api python-embedding

我有这个Visual C ++代码,加上嵌入Python的Python,当我尝试使用下面的代码运行外部Python代码时,我在调试模式下得到错误:

Unhandled exception at 0x77cf15de in CMLAir.exe (my code): 
access violation writing location 0x00000014.

当通过c ++代码调用PyRun_File函数时,会发生错误 这是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 ++中。在这种情况下,将两者结合在一起的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

错误是由于C {的fpfp的python版本之间的误解或混淆,所以,我做的是我注释了fp行,而不是我使用过:

PyObject* PyFileObject; PyFileObject = PyFile_FromString(strPythonScriptPath, "r");

这很有效!