[python-win32] passing c structure into python function
Tim Roberts
timr at probo.com
Mon Feb 15 23:14:55 CET 2010
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
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the python-win32
mailing list