ctype problem

Mark Tolonen metolone+gmane at gmail.com
Tue Jan 13 21:17:39 EST 2009


"Aaron Brady" <castironpi at gmail.com> wrote in message 
news:6197f37d-0ea0-4430-a466-2f36b2011ea8 at v42g2000yqj.googlegroups.com...
On Jan 13, 10:22 am, Grimson <grim... at gmx.de> wrote:
> hello out there,
> I have a problem with c-types.
> I made a c-library, which expects a pointer to a self defined structure.
>
> let the funtion call myfunction(struct interface* iface)
>
> and the struct:
> struct interface
> {
> int a;
> int b;
> char *c;
>
> }
>
> the Python ctype port of this structur would be:
>
> class INTERFACE(Structure):
> _fields_ = [("a" c_int),
> ("b", c_int),
> ("c", c_char)]
>
> in my python-struct a create a instance of INTERFACE
>
> myiface = INTERFACE()
> myiface.a = ctypes.c_int(80)
> myiface.b = ctypes.c_int(22)
> ...
> than I make a pointer onto it.
> p_iface = ctypes.pointer(myiface)
> and I tried it also with a reference
> r_iface = ctypes.byref(myiface)
>
> but neither myclib.myfunction(p_iface) nor myclib.myfunction(r_iface)
> works properly. The function is been called but it reads only zeros (0)
> for each parameter (member in the struct).
>
> Where is my fault?

I believe you want ("c",c_char_p), although I don't get the same error as 
you describe when I use c_char.  Below is my working code (Python 2.6.1 and 
Visual Studio 2008):

---- x.py ----
from ctypes import *

class INTERFACE(Structure):
    _fields_ = [
        ('a',c_int),
 ('b',c_int),
 ('c',c_char)
 ]

x = CDLL('x.dll')
i = INTERFACE()
i.a = 1
i.b = 2
i.c = 'hello'
x.myfunction(byref(i))

---- cl /LD /W4 x.c -> x.dll ----
#include <stdio.h>

struct interface
{
    int a;
    int b;
    char* c;
};

__declspec(dllexport)
void myfunction(struct interface* iface)
{
    printf("%d %d %s\n",iface->a,iface->b,iface->c);
}

-Mark





More information about the Python-list mailing list