Working example of extension class in C/C++ ?

Stuart D. Gathman stuart at bmsi.com
Tue Mar 11 13:47:00 EST 2003


On Tue, 11 Mar 2003 11:43:48 -0500, Marc Van Riet wrote:


> I would like to write an extension to access shared memory on Linux. I'd
> like to  implement a class with these methods : - Attach( key, size,
> flags )
> - Detach( )
> - Write( address, value)
> - Read( address ).
> I also need two members to hold values required for the shared memory
> routines in Linux :
> - an ID
> - a start address

You don't need Write/Read methods.  Just make your C object implement the
Buffer interface.  If you're lazy, you can use the built in
PyBuffer_FromReadWriteMemory C-object initialized to the address and size of
your shared memory - and make it available as a read-only attribute.
However, then you have to make sure that the memory is not detached while
references are live.

The python code can then read/write any portion of the shared memory
using standard subscripting, and read/write C values with the 'struct'
module.

It is simpler not to provide a python callable ctor for a C object.
Instead, provide a factory method in the module.  Be sure to have the
destructor for your C object detach the shared memory, in case the user
forgets to.  (But not it the user has already detached it.)

You would use it like this:

>>> import shm
>>> import struct

>>> sm = shm.attach(key,size,flags)

>>> somebytes = sm.buf[8:16]	# extract a fixed length string of bytes
# or sm[8:16] if implementing the Buffer interface directly

>>> sm.buf[2:4] = struct.pack('h',shortval) # write a C short

>>> longval = struct.unpack('l',sm.buf[4:8]) # read a C long (4 bytes)

>>> sm.detach()	# release shared memory

>>> print sm.buf
None

Below is a link to a C extension module that uses a Py_Buffer
for the record buffer of an Isam database interface.  It is tempting to
write your module for you, but I am restraining myself :-)

http://www.bmsi.com/python/cisammodule.c

-- 
Stuart D. Gathman <stuart at bmsi.com>
Business Management Systems Inc.  Phone: 703 591-0911 Fax: 703 591-6154
"Confutatis maledictis, flamis acribus addictis" - Mozart background
song for the Microsoft "Where do you want to go from here?" commercial.




More information about the Python-list mailing list