简体   繁体   中英

Problems calling Python from C++

test.py

def add(a,b):
 """  """
 print a,b,a+b
 return a+b

c program

#include <python.h>
int _tmain(int argc, _TCHAR* argv[])
{
 try
 {
  PyObject *pName,*pModule,*pDict,*pFunc,*pArgs1,*pArgs2,*pOutput;

  Py_Initialize();
  if(!Py_IsInitialized())
   return -1;
  pModule=PyImport_ImportModule("test");

  pDict=PyModule_GetDict(pModule);

  pFunc=PyDict_GetItemString(pDict,"add");
  pArgs1=Py_BuildValue("ii", 1,2); 
  //pArgs2=Py_BuildValue("i", 2); 

  pOutput=PyEval_CallObject(pFunc,pArgs1);

  int c=0;
  PyArg_Parse(pOutput, "d", &c);
  cout<<c;

  //PyRun_SimpleString("");

  Py_Finalize();
 }
 catch(exception* ex)
 {
  cout<<ex->what();
 }
 char c;
 cin>>c;
 return 0;
}

Console print nothing and closed.

What's wrong?

Thanks!

Last I checked, C doesn't have exceptions. Surely, you're not going to get any exceptions thrown by calls to the Python lib.

First, since you're using C++, you may need to include the Python lib with an extern declaration.

extern "C" {
    #include "python.h"
}

Next, since you don't have exceptions in C calls, you should test the result of each call as you go along. This will help you better understand where it's failing.

Since you're not getting a segfault or anything, I suspect you're getting to

if(!Py_IsInitialized())
 return -1;

And exiting. Instead, you could print the return value so you know what's happening.

int is_init = Py_IsInitialized();
cout << "are we initialized? " << is_init;
if(!is_init)
    return -1;

If that doesn't demonstrate the trouble, then add additional cout statements throughout your code to trace where the problem is occurring... or better yet, use a debugger and step through the code as it runs. Surely you'll find what's going wrong.

I found it contains some chinese words in first line.

#XXX

And, it also didn't work in pythonwin. Said something wrong.

So, I deleted them, and it's OK!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM