Problem generating functions from C strings

I

Ian Glover

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top