[python-win32] passing c structure into python function [SEC=PERSONAL]

Andrew MacIntyre Andrew.MacIntyre at acma.gov.au
Tue Feb 16 01:24:32 CET 2010


> On Behalf Of Tim Roberts
> 
> a h wrote:
> >
> > thnks. i have used struct.unpack function for small c structure as
the
> > way Tim has suggested.
> > i have an complex C structure, and passing this structure as a
string
> > and then using struct.unpack() is very tough job.and also i have
> > pointers in my struct now.
> >
> > i want that i have structure say like
> > struct emp
> > {
> >     int id;
> >     ...
> > {
> > and i just pass this into python function by converting c structure
> > into python PyObject and using PyObject_CallObject() i can pass this
> > pyobject.
> >
> > In python script i want that i can simply print these values like
> > def func(s):
> >     print s.id <http://s.id>
> >
> > Is it possible to do this way?.
> 
> Yes, it's possible to create an object in your C code, then add
> attributes to it one by one to match your structure, but the code to
do
> so is rather tedious.  In my opinion -- and it is only my opinion! --
> you're better off using a Python wrapper to create and populate the
object.
> 
> Have you encountered the "swig" library?  Swig can read C header
files,
> and generate C and Python code that exposes the structures and
function
> calls to Python.  If you need to do this a lot, it might be worthwhile
> to learn about it.  It is a difficult tool to learn, but once you get
> it, it's incredibly handy.  Much of PyWin32 is automatically generated
> by swig (with careful tweaking).
> 
>     http://www.swig.org/Doc1.3/Python.html

Pyrex and Cython might also be useful alternatives for the OP's purpose.

-------------------------> "These thoughts are mine alone!" <---------
Andrew MacIntyre           Operations Branch
tel:   +61 2 6219 5356     Communications Infrastructure Division
fax:   +61 2 6253 3277     Australian Communications & Media Authority
email: andrew.macintyre at acma.gov.au            http://www.acma.gov.au/


If you have received this email in error, please notify the sender immediately and erase all copies of the email and any attachments to it. The information contained in this email and any attachments may be private, confidential and legally privileged or the subject of copyright. If you are not the addressee it may be illegal to review, disclose, use, forward, or distribute this email and/or its contents.
 
Unless otherwise specified, the information in the email and any attachments is intended as a guide only and should not be relied upon as legal or technical advice or regarded as a substitute for legal or technical advice in individual cases. Opinions contained in this email or any of its attachments do not necessarily reflect the opinions of ACMA.


More information about the python-win32 mailing list