tags:

views:

121

answers:

2

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!

+3  A: 

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.

Jason R. Coombs
@Jason R. Coombs: pArgs1=Py_BuildValue("ii", 1,2); pOutput=PyEval_CallObject(pFunc,pArgs1);Is it right?
Begtostudy
I think you need pArgs1=Py_BuildValue("(ii)", 1, 2); Also, you need to Py_DECREF(pArgs1); after you're done with it (after PyEval_CallObject).
Jason R. Coombs
pModule=PyImport_ImportModule("test");this line return nullI put the py with the output exe, is thar right?Why module import error?
Begtostudy
It's hard to say. One thing you might try is set an environment variable PYTHONPATH=/mylibs (or whatever) and then put test.py in that directory. Also, make sure your test.py is valid for the Python version you're using. If you're compiling against Python 2.x, you should be fine, otherwise, use 'print(a,b,a+b)'
Jason R. Coombs
A: 

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!

Begtostudy