Setting value of Python variable in a Python C extension

M

MD

Hi,
I have a function developed in C that is being used as a Python
extension. The function is being passed a variable from the Python
program. Is it possible to change the value of this variable from
within the C function?

Thanks,
-MD
 
C

Carsten Haese

Hi,
I have a function developed in C that is being used as a Python
extension. The function is being passed a variable from the Python
program. Is it possible to change the value of this variable from
within the C function?

That question is ill-defined because Python doesn't have variables.
Python has objects and names. "Change the value of this variable" can
either mean that you want to mutate an object that's passed by the
caller, which you can do as long as the object is mutable, or you want
to rebind a name in the caller's namespace, which you can't do.

Why do you think your function needs to have side-effects instead of
simply returning a return value?
 
M

MD

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?

Thanks,
-Manas
 
C

Carsten Haese

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,
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top