Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > C API (embedded Python): How to get and set named variables

Reply
Thread Tools

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

 
 
mrabens@gmail.com
Guest
Posts: n/a
 
      09-10-2007
>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.

 
Reply With Quote
 
 
 
 
Farshid Lashkari
Guest
Posts: n/a
 
      09-10-2007
http://www.velocityreviews.com/forums/(E-Mail Removed) 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
 
Reply With Quote
 
 
 
 
Martoon
Guest
Posts: n/a
 
      09-10-2007
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!

 
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
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Put variables into member variables or function variables? tjumail@gmail.com C++ 9 03-23-2008 04:03 PM
dynamically named variables or Constants Tom V. Ruby 9 05-07-2007 07:50 PM
Named regexp variables, an extension proposal. Paddy Python 8 05-14-2006 09:08 PM
Named fixtures and automatic instance variables; newbie prob Mike Blyth Ruby 1 03-18-2006 07:32 AM



Advertisments