Setting value of Python variable in a Python C extension

Carsten Haese carsten at uniqsys.com
Mon Oct 1 12:59:28 EDT 2007


On Mon, 2007-10-01 at 09:42 -0700, MD wrote:
> Hi Carsten,
>     Thanks for your reply. I am a newbie on Python so your help is
> much appreciated. My program structure is basically like this .....
> (rough representation)
> test.py
>    var1 = ""
>    rc = func1 (var1)
> 
> test.c
>     func1(*v1) {
>     strcpy(v1, "Hello World");
> }
> 
> So basically I want to modify value of "var1" in the function "func1"
> defined in test.c. Is this possible?

No, that requires altering the caller's namespace, which is not
possible. Why do you think you need to do that? Is your problem that
func1 essentially returns two values and you don't know how to achieve
that? In that case, be advised that you can return a tuple to the
caller, along these lines:

test.py
  rc, var1 = func1()

test.c
  func1(void) {
    /* ... */
    return Py_BuildValue("(is)", rc, v1);
    /* I'm assuming 'rc' is an integer, adjust the above line to fit
what rc actually is. */
  }

Also, since you are a newbie, I'd like to suggest you work through the
Python tutorial and learn what you can do in pure Python first before
moving on to the more advanced topic of writing C extensions.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list