Question about embedding Python

Del Iablo noreply at nowhere.com
Mon Mar 17 04:18:45 EST 2003


I've got Python running and working with my engine, to the point that I can
define variables in Python scripts, run them with my C++ code, and then get
those variables for run-time use in the C++ code.

In order to do this I've tried encapsulating the Python variables inside a
script variable structure in the C++ code, called ScriptVariable. This
struct contains a PyObj pointer to the variable in the dictionary. I can
then do runtime conversion (e.g., PyInt_AsLong) to get the value.

I'm curious as to why this pointer becomes invalid after re-defining the
variable. This is what I do:

I have a script file, startup.py:

width=640
height=480

I run this with PyRun_File, and I can lookup width and height in the
dictionary, create the ScriptVariables, all works fine. I can get the values
and they match the script.

I then run the command line (from the debugger) "width=1024 height=768". I
bust it up into individual statements and send them to PyRun_String. I pass
in the same dictionary pointer to both Python functions, and there is
currently only one dictionary.

If I do not re-get the pointers to the variables before attempting to cast
them, the program crashes trying to dereference the second variable (the
first variable ends up with the second variable's new value). But if I force
the ScriptVariable structure to re-find its Python variable in the
dictionary every time I try to convert it, it works fine.

The reason for this eludes me. Is Python actually creating two variables, or
is it dereferencing the previous variable, causing it to be destroyed?

I'd like to avoid doing the dictionary lookup every time if possible. Am I
just stuck doing it every time?

Thanks.







More information about the Python-list mailing list