C API (embedded Python): How to get and set named variables

Discussion in 'Python' started by mrabens@gmail.com, Sep 10, 2007.

  1. Guest

    >From the C API (I'm using Python embedded), how can I get and set the
    value of named variables? Right now, I'm using hacks like
    PyRun_SimpleString("foobar = 12\n"), but I'd really like to access the
    named objects directly.
     
    , Sep 10, 2007
    #1
    1. Advertising

  2. wrote:
    >>From the C API (I'm using Python embedded), how can I get and set the

    > value of named variables? Right now, I'm using hacks like
    > PyRun_SimpleString("foobar = 12\n"), but I'd really like to access the
    > named objects directly.
    >


    You can use the following C functions to set/get named attributes of an
    object:

    PyObject_SetAttrString
    PyObject_GetAttrString

    If the attributes belong to the global scope of a module, then you can
    use "PyImport_AddModule" to get a handle to the module object. For
    example, if you wanted to get the value of an integer in the __main__
    module named "foobar", you would do the following:

    PyObject *m = PyImport_AddModule("__main__");
    PyObject *v = PyObject_GetAttrString(m,"foobar");

    int foobar = PyInt_AsLong(v);

    Py_DECREF(v);

    You will probably want to add some error checking in your code.

    -Farshid
     
    Farshid Lashkari, Sep 10, 2007
    #2
    1. Advertising

  3. Martoon Guest

    Thank you! Just what I needed.

    I came across the PyObject_*AttrString() functions earlier when
    searching through the docs, and I thought I was in the right area, but
    I didn't know what object I was supposed to set the attribute for.
    Now I see that it's a module object. It all makes sense now. Thanks!
     
    Martoon, Sep 10, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Praveen, Tayal (IE10)
    Replies:
    0
    Views:
    380
    Praveen, Tayal (IE10)
    Mar 17, 2005
  2. Colin Paul Gloster
    Replies:
    48
    Views:
    1,895
    Colin Paul Gloster
    Apr 10, 2007
  3. iwl
    Replies:
    3
    Views:
    660
  4. Replies:
    0
    Views:
    282
  5. Thomas Dodds

    Databind an embedded control in an embedded datagrid

    Thomas Dodds, Jul 26, 2004, in forum: ASP .Net Datagrid Control
    Replies:
    0
    Views:
    405
    Thomas Dodds
    Jul 26, 2004
Loading...

Share This Page