dynamic classes and duck typing

Walter Bright newshound1 at digitalmars.com
Tue Dec 1 17:16:20 PST 2009


bearophile wrote:
> Walter Bright:
> 
>> Ok, does this work:
>> 
>> p = libc.malloc(100); *p = 3;
>> 
>> ? Or this:
>> 
>> struct S { int a; char b; }; S s; libc.fillInS(&s);
> 
> The purpose of ctypes is to interface Python with C libs, it's a
> quite well designed piece of software engineering. This is how you
> can do what you ask for:
> 
> from ctypes import POINTER, Structure, cdll, c_int, c_char
> 
> libc = cdll.msvcrt # on Windows # libc = CDLL("libc.so.6") # on linux
>  malloc = libc.malloc
> 
> malloc.restype = POINTER(c_int) p = malloc(100) p[0] = 3
> 
> #-----------------
> 
> class S(Structure): _fields_ = [("a", c_int), ("b", c_char)]
> 
> s = S() # AttributeError: function 'fillInS' not found 
> libc.fillInS(byref(s))
> 
> Bye, bearophile

Doable, yes, simple, no. For example, it's clear it cannot be linked 
directly to C. The C code must be installed into a shared library first.



More information about the Digitalmars-d mailing list