Hard typecasts in ctypes possible? int -> "pointer to struct" for example
Question: I have am inside a callback that allows me to access the pointers passed to it
as `int` (i.e. the Python `type()` function returns `int`).

What so I have to do if I want convert this into a pointer of a `struct` whose
layout I know and can define as a `ctypes` class. Say I have this already:

    
    
    class data_t(Structure):
      _fields = [ ("foo", c_int), ("bar", c_wchar_p), ("baz", c_char_p) ]
    

How can a variable `x` for which `type(x)` gives the output `int` now be cast
into a pointer to the above `struct` type?

**The gist:** I have no influence on the declaration of the callback function
or the declaration of the arguments I get to see, so I need some way to get
from the Python `int` type to a `ctypes` pointer and access the `struct`
members from there ...

This is Python 2.6, but I reckon most 2.x will be similar enough at least. I
can't get rid of this version requirement as it is embedded into a product
that requires _this particular_ Python version.


Answer: You can use `ctypes.cast`, or just declare the callback to return a
`POINTER(data_t)`. Examples of both below and tested on Python 2.7 and Python
3.2:

### test DLL code (Windows)

    
    
    typedef struct data {
        int foo;
        wchar_t* bar;
        char* baz;
    } data_t;
    
    typedef void (*CALLBACK)(data_t* p);
    
    CALLBACK g_callback = 0;
    
    extern "C" __declspec(dllexport) void set_callback(CALLBACK f)
    {
        g_callback = f;
    }
    
    extern "C" __declspec(dllexport) void call_callback()
    {
        data_t data;
        data.foo = 123;
        data.bar = L"马克";
        data.baz = "Mark";
        g_callback(&data);
    }
    

### Python

    
    
    from ctypes import *
    
    class data_t(Structure):
        _fields_ = [
            ("foo", c_int),
            ("bar", c_wchar_p),
            ("baz", c_char_p)]
    
    dll = CDLL('test')
    
    @CFUNCTYPE(None,c_int)
    def callback(n):
        p = cast(n,POINTER(data_t)).contents
        print(p.foo,p.bar,p.baz)
    
    @CFUNCTYPE(None,POINTER(data_t))
    def callback2(n):
        p = n.contents
        print(p.foo,p.bar,p.baz)
    
    dll.set_callback(callback)
    dll.call_callback()
    
    dll.set_callback(callback2)
    dll.call_callback()
    

### Output

    
    
    123 马克 b'Mark'
    123 马克 b'Mark'
    

