Problem generating functions from C strings

Ian Glover ian.glover at SYRRIS.com
Tue Aug 31 11:30:51 CEST 2004


Hi there,

I'm having problems trying to link C++ and Python. What I want to do is have the C provide a function from a string and then run the function. What I've currently got is

  PyObject* lpyModuleName = PyString_FromString( "__main__" ); // New Ref.
  assert( lpyModuleName );
  PyObject* lpyMain = PyImport_Import( lpyModuleName ); // New Ref.
  assert( lpyMain );
  PyObject* lpyDict = PyModule_GetDict( lpyMain ); // Borrowed.
  assert( lpyDict );
  PyObject* lpyLocals = PyDict_New();

  std::string lCode =
    "import config\n"
    "def PyOperator(parameter):\n"
    "    v1 = config.GetHardware(\"valve\", 1)\n"
    "    v2 = config.GetHardware(\"valve\", 2)\n"
    "    v1.set_position( 1 )\n"
    "    v2.get_position( 1 )\n";

  PyRun_String( lCode.c_str(), Py_file_input, lpyDict, lpyLocals );


  PyObject* lpyFuncName = PyString_FromString( "PyOperator" ); // New Ref.
  assert( lpyFuncName );
  PyObject* lpyFunction = PyDict_GetItem( lpyDict, lpyFuncName ); // Borrowed.

// *** This assertion fails ***
  assert( lpyFunction );
// ****************************

  assert( PyCallable_Check( lpyFunction ) );

  PyObject* lpyArguments = Py_BuildValue("(d)", 2);
  assert( lpyArguments );
  PyObject* lpyResult = PyEval_CallObject( lpyFunction, lpyArguments );

  Py_DECREF( lpyResult );
  Py_DECREF( lpyArguments );
  Py_DECREF( lpyFuncName );
  Py_DECREF( lpyMain );
  Py_DECREF( lpyModuleName );
  Py_DECREF( lpyLocals );


This is in a C++ extension module that and being called via another function that's being exposed. It seems that the function isn't get put in the scope I'd expect. And indeed if I comment out the lines that try and get it so that the assert failure doesn't occur and I can poke around the scopes via dir() I can't see it. So where is it being put? or am I doing this very wrong?

Thanks

Ian



More information about the Python-list mailing list