Python C Object Comparison

Craig Ringer craig at postnewspapers.com.au
Fri Jan 7 00:43:29 EST 2005


On Thu, 2005-01-06 at 18:34, Anand K Rayudu wrote:

> Here is my python code
> 
> import myModule
> 
> a=myModule.myAPI1("1")
> b=myModule.myAPI2("name")
> 
> # basically both above functions return same C pointer.
> # so i want to compare
> if(a==b): print "They are same"
> else : print "They are different"
> 
> python always prints they are different,
> I guess this is because in python layer we create PythonCObject for 
> every C pointer, and that is how it is exposed to python. Though both 
> the APIs are returning the same C pointer, they are different instances 
> of PythonCObject.

That sounds likely to me.

> So i guess that is the reason comparison is failing.
> How ever is it possible to make python to compare actual C pointer, 
> rather than the PythonCObject Pointer.

You might be able to subclass PyCObject and work with your subclassed
version (that adds a __eq__ method). In the end, though, I don't think
that's the right path to proceed down.

My understanding is that CObjects are for passing pointers through
Python code in a safe way. I don't think they're really intended for
uses where the Python code is actually working with the objects, only
pass them around as opaque objects.

If you want to actually work with the objects you're passing around, I'd
think about implementing my own type that better fits the API my
extension module wants to present to Python code.

I'm using PyCObjects as a temporary ugly hack in an embedded app I'm
working on... but it's seriously ugly. What I should do, and will soon
do now that I've tested the concept of what I'm doing and it works, is
move all my functions into a class and make the class own and manage the
C++ object (and pointer to it) that it owns.

Perhaps that's a better solution for you too? 

If you want any opinions from folks here about the best way to solve
your problem, you'll probably need to explain a bit more of your problem
- like what your extension module is doing that makes it have to pass
PyCObjects around and get Python code to work with them.

--
Craig Ringer




More information about the Python-list mailing list