Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Problem generating functions from C strings

Reply
Thread Tools

Problem generating functions from C strings

 
 
Ian Glover
Guest
Posts: n/a
 
      08-31-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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Strings, Strings and Damned Strings Ben C Programming 14 06-24-2006 05:09 AM
Generating random strings without duplicates eric.gagnon@loto-quebec.com C++ 7 07-13-2005 10:06 AM
generating strings Eddie C++ 7 08-28-2004 05:31 AM
generating strings Eddie C Programming 3 08-26-2004 06:21 PM
please help me in distinguish redefining functions, overloading functions and overriding functions. Xiangliang Meng C++ 1 06-21-2004 03:11 AM



Advertisments