C++ and Python

Gordon McMillan gmcm at hypernet.com
Tue Aug 31 20:38:56 CEST 1999

Sven Drescher writes:
> I have a little problem. It's really urgent. I wrote a program with
> threads. One thread is the Python/Tk loop with my graphical user
> interface and the other is an work thread.
> Now my question:
> How can I get the entrie-variables of python in my work thread.
> I know such functions like PyArg_ParseTuple and so on to convert the
> values, but is there a possibility to have an C-reference variable
> to a python variable or so?

Short answer: "no".

Problem 1:  Difference between reference semantics and slot 

 foo = "I'm a string"
 foo = foo + ", but now I'm longer"

In C, the first foo has no relationship to the second. In a case like 
this (references to immutables where the reference may change), you 
have to look up "foo" in the appropriate dictionary.

Problem 2: scope. What dictionary does it live in?

Well, I think we can assume you're only talking about globals. In 
which case, the longer answer is "yes, sort of". You can of a 
module's dictionary in your C code and look things up in it. You 
could even optimize this (only look it up once) for those cases where 
you know the reference doesn't change, but that's a bit risky:

 a = []
 a.append(3) # reference doesn't change
 a = a[:] # oops, reference changed.

As long as you don't release the interpreter lock in your C code, you 
won't have to worry much about race conditions (everything you do 
will be atomic as far as Python is concerned). If you do release the 
interpreter lock, make sure any Python variables are in a consistent 
state, and don't touch them until you've re-aquired the lock.

- Gordon

More information about the Python-list mailing list