Using C++ and ctypes together: a vast conspiracy? ;)

Dave Angel davea at ieee.org
Wed Jun 3 01:43:04 CEST 2009


Joseph Garvin wrote:
> So I was curious whether it's possible to use the ctypes module with
> C++ and if so how difficult it is. I figure in principal it's possible
> if ctypes knows about each compiler's name mangling scheme. So I
> searched for "ctypes c++" on Google.
>
> The third link will be "Using ctypes to Wrap C++ Libraries". If you
> follow the link, it's broken. If you view the cache of the link, it's
> someone pointing to another blog, retrograde-orbit.blogspot.com,
> saying they discovered a way to do it easily. If you follow that link,
> you get taken a page does not exist error.
>
> Clearly there's some way to use ctypes with C++ and there's a vast
> conspiracy preventing it from reaching the masses ;) What's even
> stranger is that this link, despite being broken, has seemingly been
> near the top of google's results for these terms for a couple weeks
> (that's when I last tried), as if there were some underground group of
> rebels trying to hint the truth to us... ;)
>
> More seriously -- how difficult is it to use ctypes instead of saying,
> boost::python, and why isn't this in a FAQ somewhere? ;)
>
>   
There are two possibilities here.  You might have an existing DLL, 
written entirely in C++, with thoroughly mangled exports.   Or you might 
have a body of code, to which you're willing to make modifications for 
the interface.  It's only the second I would attack with ctypes.  In 
fact, the name mangling itself varies between versions of the same 
compiler, never mind between different brands.

You should be able to export a class factory, defined as an extern("c"), 
and use that to get into the DLL.  Once you have that, you can call any 
virtual functions of the class without any additional
 exports or name mangling needed.  As long as the methods you're using 
are virtual, and singly inherited, it's just a question of walking the 
vtable.  So you should be able to build wrappers, using ctypes, for each 
of those methods.

Note:  I haven't actually done it, as the machine with the C++ compiler 
installed as been down for longer than I've had Python, and I haven't 
wanted C++ enough to want to install it on my notebook computer.  But 
this is the approach I'd try.





More information about the Python-list mailing list