473,725 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PyRun_String and related functions causing garbage when calling a parsed function from C.

Hi I'm getting extremely odd behavior. First of all, why isn't
PyEval_EvalCode documented anywhere? Anyway, I'm working on
blender's
python integration (it embeds python, as opposed to python embedding
it). I have a function that executes a string buffer of python code,
fetches a function from its global dictionary then calls it.

When the function code returns a local variable, PyObject_Call()
appears
to be returning garbage. Strangely this is only happening with
internal
blender types, yet try however I might I can't find any refcounting
errors to account for this. The initial implementation used the same
dictionary for the global and local dicts. I tried using separate
dicts, but then the function wasn't being called at all (or at least I
tested it by putting a "print "bleh"" in there, and it didn't work).
Also, when I printed the refcount of the garbage data, it was garbage
as
well (so the entire piece of memory is bad, not just the data
portion).

I've tested with both python 2.4 and 2.5. Mostly with 2.4. This bug
may be cropping up in other experimental blender python code as well.

Here's the code in the string buffer:
#BPYCONSTRAINT
from Blender import *
from Blender.Mathuti ls import *
print "d"
def doConstraint(in mat, tarmat, prop):
a = Matrix()
a.identity()
a = a * TranslationMatr ix(Vector(0, 0, 0))
print "t"
a = tarmat
return inmat

print doConstraint(Ma trix(), Matrix(), 0)

Here's the code that executes the string buffer:

PyObject *RunPython2( Text * text, PyObject * globaldict, PyObject
*localdict )
{
char *buf = NULL;

/* The script text is compiled to Python bytecode and saved at
text->compiled
* to speed-up execution if the user executes the script multiple times
*/

if( !text->compiled ) { // if it wasn't already compiled, do it
now
buf = txt_to_buf( text );

text->compiled =
Py_CompileStrin g( buf, GetName( text ),
Py_file_input );

MEM_freeN( buf );

if( PyErr_Occurred( ) ) {
BPY_free_compil ed_text( text );
return NULL;
}

}
return PyEval_EvalCode ( text->compiled, globaldict, localdict );
}
.. . .and heres the (rather long, and somewhat in a debugging state)
function that calls the function in the script's global dictionary:

void BPY_pyconstrain t_eval(bPythonC onstraint *con, float obmat[][4],
short ownertype, void *ownerdata, float targetmat[][4])
{
PyObject *srcmat, *tarmat, *idprop;
PyObject *globals, *locals;
PyObject *gkey, *gval;
PyObject *retval;
MatrixObject *retmat;
Py_ssize_t ppos = 0;
int row, col;

if ( !con->text ) return;

globals = CreateGlobalDic tionary();

srcmat = newMatrixObject ( (float*)obmat, 4, 4, Py_NEW );
tarmat = newMatrixObject ( (float*)targetm at, 4, 4, Py_NEW );
idprop = BPy_Wrap_IDProp erty( NULL, &con->prop, NULL);

/* since I can't remember what the armature weakrefs do, I'll just
leave this here
commented out. Since this function was based on pydrivers.
if( !setup_armature _weakrefs()){
fprintf( stderr, "Oops - weakref dict setup\n");
return result;
}
*/
retval = RunPython2( con->text, globals, globals);

if (retval) {Py_XDECREF( retval );}

if ( retval == NULL ) {
BPY_Err_Handle( con->text->id.name);
ReleaseGlobalDi ctionary( globals );

/*free temp objects*/
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
return;
}

/*Now for the fun part! Try and find the functions we need.*/
while ( PyDict_Next(glo bals, &ppos, &gkey, &gval) ) {
if ( PyString_Check( gkey) && strcmp(PyString _AsString(gkey) ,
"doConstraint") ==0 ) {
if (PyFunction_Che ck(gval) ) {
retval = PyObject_CallOb ject(gval,
Py_BuildValue(" OOO",
srcmat, tarmat, idprop));
Py_XDECREF( retval );
} else {
printf("ERROR: doConstraint is supposed to be a
function!\n");
}
break;
}
}

if (!retval) {
BPY_Err_Handle( con->text->id.name);
/*free temp objects*/
ReleaseGlobalDi ctionary( globals );

Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
return;
}

if (!PyObject_Type Check(retval, &matrix_Type )) {
printf("Error in pyconstraint: Wrong return type for a
pyconstraint!\n ");
ReleaseGlobalDi ctionary( globals );

Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return;
}

retmat = (MatrixObject*) retval;
if (retmat->rowSize != 4 || retmat->colSize != 4) {
printf("Error in pyconstraint: Matrix is the wrong size!\n");
ReleaseGlobalDi ctionary( globals );

Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return;
}

//this is the reverse of code taken from newMatrix().
for(row = 0; row < 4; row++) {
for(col = 0; col < 4; col++) {
if (retmat->wrapped) obmat[row][col] =
retmat->data.blend_dat a[row*4+col]; //[row][col];
else obmat[row][col] = retmat->data.py_data[row*4+col];
//[row][col];

}
}

/*clear globals*/
//ReleaseGlobalDi ctionary( globals );

/*free temp objects*/
//Py_XDECREF( idprop );
//Py_XDECREF( srcmat );
//Py_XDECREF( tarmat );
//Py_XDECREF( retval );
//PyDict_Clear(lo cals);
//Py_XDECREF(loca ls);
}

Joe

May 13 '07 #1
1 2211
En Sun, 13 May 2007 17:58:17 -0300, <jo****@gmail.c omescribió:
Hi I'm getting extremely odd behavior. First of all, why isn't
PyEval_EvalCode documented anywhere? Anyway, I'm working on
blender's
python integration (it embeds python, as opposed to python embedding
it). I have a function that executes a string buffer of python code,
fetches a function from its global dictionary then calls it.
Why don't you use a documented function like PyRun_String or similar, as
in the subject line?
/*Now for the fun part! Try and find the functions we need.*/
while ( PyDict_Next(glo bals, &ppos, &gkey, &gval) ) {
if ( PyString_Check( gkey) && strcmp(PyString _AsString(gkey) ,
"doConstraint") ==0 ) {
if (PyFunction_Che ck(gval) ) {
retval = PyObject_CallOb ject(gval,
Py_BuildValue(" OOO",
srcmat, tarmat, idprop));
Py_XDECREF( retval );
} else {
printf("ERROR: doConstraint is supposed to be a
function!\n");
}
break;
}
}
I'd use PyDict_Get_Item _String (iterating over a dict just to locate a key
is rather silly).
And, if you are going to use the return value from PyObject_CallOb ject
(retval), don't decref it!!! (you even decref it twice).

--
Gabriel Genellina

May 14 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2152
by: Chuck Ritzke | last post by:
I keep asking myself this question as I write class modules. What's the best/smartest/most efficient way to send a large object back and forth to a class module? For example, say I have a data access module that creates a large disconnected dataset from a database. I want to pass that dataset back to the calling program. And then perhaps I want to send that dataset to another class module. At first it seems that the "object oriented"...
26
45515
by: Dave Hammond | last post by:
In document "A.html" I have defined a function and within the document body have included an IFRAME element who's source is document "B.html". In document "B.html" I am trying to call the function defined in "A.html", but every attempt results in an "is not a function" error. I have tried to invoke the function using parent.document.funcname(), top.document.funcname(), and various other identifying methods, but all result in the above...
4
6648
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause potential problems for thread-safety. So far, I'm only confused. I need a proper explanation for the concept so I can understand how to write thread-safe functions in the future. My apologies for posting a long routine.
16
1993
by: G Patel | last post by:
Hi, If I want to call functions that don't return int without declaring them, will there be any harm? I only want to assign the function(return value) to the type that it returns, so I don't see how the return value comes to play here. Ex
19
4257
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
9
8298
by: TheOne | last post by:
Would anyone please point me to a list of reentrant C library functions? I want to know which C library functions are safe to use inside a signal handler across all platforms. Does GNU C library make few other functions reentrant on Linux platform? I have searched a lot on the web for it but without any success. Man page of signal(2) has listed system calls (POSIX 1003.1-2003 list) which are safe(reentrant) but thats not sufficient for...
5
2515
by: Michael Moreno | last post by:
Hello, In a class I have this code: public object Obj; If Obj is a COM object I would like to call in the Dispose() method the following code: System.Runtime.InteropServices.Marshal.ReleaseComObject(Obj);
4
4207
by: Stuart | last post by:
I've written my own python modules with the C API, called dlfl. I've now embedded a python interpreter into my Qt application. I am able to execute multiline/singleline blocks and it has no problems remembering definitions from one execute to the next. The problem arises when i try and use a dlfl method inside a def block. For example def x( ): print faces(0) faces is a method in dlfl. If I were to just type "print faces(0)" it would...
7
4078
by: Tom Davis | last post by:
I am having a problem where a long-running function will cause a memory leak / balloon for reasons I cannot figure out. Essentially, I loop through a directory of pickled files, load them, and run some other functions on them. In every case, each function uses only local variables and I even made sure to use `del` on each variable at the end of the loop. However, as the loop progresses the amount of memory used steadily increases. I...
0
8874
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8748
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9092
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6695
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4506
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4775
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3212
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2622
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.