faqts : Computers : Programming : Languages : Python : Common Problems : C/C++ Code

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

21 of 24 people (88%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I call Python scripts from C/C++ program?
Is it possible for C to call Python routines and vice-versa?

Jun 9th, 2000 00:58
unknown unknown, Phil Austin


Here's a solution using CXX (http://CXX.sourceforge.net).  

You'll want the current CVS snapshot, as there have been several
bugs fixed in CXX-4.2

Note: put FibSeries into a file called myfun.py:

callable.cxx:

#include "Python.h"
#include "CXX_Objects.h"
#include <iostream>

using namespace Py;
using namespace std;

extern "C" void Py_Initialize();
extern "C" void Py_Finalize();

int
main(int argc, char* argv[])
{
  Py_Initialize();
  Module myfun("myfun");
  Callable fib = myfun.getAttr("FibSeries");
  Tuple argtuple(3);
  argtuple[0]=Int(2);
  argtuple[1]=Int(2);
  argtuple[2]=Int(30);
  Object output = fib.apply(argtuple);
  cout << List(output) << endl;
  Py_Finalize();
  return 0;
}


Compiling and executing this gives:

<peacock ~> callable
2
4
6
10
16
26
[2, 4, 6, 10, 16, 26]