get class instance from C++ extension?

Toshiya Kawakami kawakami at lead.dion.ne.jp
Fri Jun 15 02:55:18 EDT 2001


I am trying to call extension C++ modules from embedded python,
and want to know how to return a class (instance) defined in python
from C++ to caller in python.

I know some examples that show C++ returns an integer to python,
but they don't explain about returning a class.
What I want to do is something like following codes.
How can I return a same information with a python class from C++?

----begin of "test1.py"
import myext1

class c1:
  a1 = 1
  a2 = 2
  def m1():
    return a1 + a2

### this is ordinary way to get instance of class c1 as x.
x = c1()
### I want to call C++ extension and get calss c1 instance to y
y = myext.meth1( 5, 6, 7.2 )
### and want to print attributes of the got y.
print y.a1, y.a2, y.m1()
----end of "test1.py"

----begin of ext1.cpp (fragment)
#include "python.h"

struct PyMethodDef ext1_methods[] = {
 { "meth1", meth1, METH_VARARGS },
 { NULL, NULL }
};

aaaa{
  ::Py_Initialize();
  ::PyImport_AddModule( "myext1" );
  ::Py_InitModule( "myext1", ext1_methods );
  char *filename1 = "test1.py";
  if ( ( fp = fopen( filename1, "r" ) ) == NULL ) {
     ...
  }
  ::PyRun_SimpleFile( fp, filename1 );
}

static PyObject *
meth1( PyObject *self, PyObject *args )
{
  char *command;
  int sts;

  if ( !PyArg_ParseTuple( args, "iif", &i1, &i2, &f1 ) )
    return NULL;

  //
  // do something here using i1, i2, f1.
  //

  // This example returns an integer to python.
  //  I want to return not an integer but the same structure with
  // the class c1 defined in test1.py file. How can I do that?
  return Py_BuildValue( "i", 0 );   // <--- this is not what i want to do
}

----end of ext1.cpp (fragment)





More information about the Python-list mailing list