How do I use python object in C++

lixinyi.23 at gmail.com lixinyi.23 at gmail.com
Wed Sep 24 07:29:54 CEST 2008


On 9月24日, 午後1:15, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com>
wrote:
> On Sep 23, 11:06 pm, "Aaron \"Castironpi\" Brady"
>
>
>
> <castiro... at gmail.com> wrote:
> > On Sep 23, 9:30 pm, lixinyi... at gmail.com wrote:
>
> > > If the PyObject is a PyList, and all list items are strings,
> > > say a=['aaa','bbb','ccc']
>
> > > How can I have a
> > > myArray[0] = "aaa"
> > > myArray[1] = "bbb"
> > > myArray[2] = "ccc"
> > > in C++?
>
> > > Do I have to
> > > use PyModule_GetDict() to get the dict first?
> > > what about the next?
>
> > > > What do you know about the contents of 'argc' and 'argv'?  If it's
> > > > impossible with Py_Main, can you use one of the other entry points?
>
> > > > If you've never manipulated PyObject* objects in C, they can be
> > > > hairy.  Even if you know 'a' is a sequence, its contents are still all
> > > > PyObject*s, which you can access via PyList_... and PySequence_
> > > > functions.
>
> > This one writes '[aaa, bbb, ccc]' to the console in two different
> > ways.
>
> > #include <Python.h>
>
> > int main() {
> >     PyObject *list, *listrepr;
> >     Py_Initialize();
>
> >     /* first */
> >     list= PyList_New( 3 );
> >     PyList_SetItem( list, 0, PyString_FromString( "aaa" ) );
> >     PyList_SetItem( list, 1, PyString_FromString( "bbb" ) );
> >     PyList_SetItem( list, 2, PyString_FromString( "ccc" ) );
>
> >     listrepr= PyObject_Repr( list );
> >     printf( "%s\n", PyString_AsString( listrepr ) );
>
> >     Py_DECREF( listrepr );
> >     Py_DECREF( list );
>
> >     /* second */
> >     list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" );
> >     listrepr= PyObject_Repr( list );
> >     printf( "%s\n", PyString_AsString( listrepr ) );
>
> >     Py_DECREF( listrepr );
> >     Py_DECREF( list );
>
> >     Py_Finalize();
> >     return 0;
>
> > }
>
> > Did you want to execute some Python code, and examine variables it
> > creates?
>
> Here's a third way:
>
>     PyObject *list, *listrepr, *dict, *result, *name;
>     /* third */
>     dict= PyDict_New( );
>     result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]",
>         Py_file_input, dict, NULL );
>     name= PyString_FromString( "myarray" );
>     list= PyDict_GetItem( dict, name );
>     listrepr= PyObject_Repr( list );
>     printf( "%s\n", PyString_AsString( listrepr ) );
>
>     Py_DECREF( dict );
>     Py_DECREF( result );
>     Py_DECREF( name );
>     Py_DECREF( listrepr );
>     Py_DECREF( list );
>
> PyRun_String runs a namespace, 'dict', which holds the variables.


Thanks! it helps.

I know how to read from python now.

main_module = PyImport_AddModule("__main__");
global_dict = PyModule_GetDict(main_module);
pyObject = PyDict_GetItem(global_dict,key);


it will require lots of type checking, but it's fine to me.




More information about the Python-list mailing list