开发者

Problems calling Python from C++

开发者 https://www.devze.com 2023-01-04 06:29 出处:网络
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[])

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消