ctypes, function pointers and a lot of trouble

Nick Craig-Wood nick at craig-wood.com
Mon Jun 2 18:30:22 CEST 2008


Matt <mr.edel at gmx.at> wrote:
>  class MemStreamData(Structure):
>       _fields_ = [("mode", c_byte),
>                        ("lPos", c_uint),
>                        ("dwVisibleSize", c_uint),
>                        ("dwBufferSize", c_uint),
>                        ("cpBuffer", POINTER(c_char))]
> 
>  class FilStreamData (Structure):
>       _fields_ = [("szFileName", c_char * 30),
>                        ("hFile", c_uint)]
> 
> 
> 
>  and the code to fill all that with the right data is the following:
> 
> 
>       datainfo = cdReleaseImageInfo()
> 
>       databuf = c_char * 100000
>       cbuffer=MemStreamData()
>       cbuffer.mode = c_byte(0)
>       cbuffer.lPos = c_uint(0)
>       cbuffer.dwVisibleSize = c_uint(100000)
>       cbuffer.dwBufferSize = c_uint(100000)
> 
>  #this line does not work, wrong datatype!?
>       cbuffer.cpBuffer = POINTER(databuf)
[snip]
>  Does anyone see where the errors are?

  databuf = c_char * 100000

Is a type not an instance...

You need to instantiate it, eg

  >>> from ctypes import *
  >>> class MemStreamData(Structure):
  ...     _fields_ = [("cpBuffer", POINTER(c_char))]
  ...
  >>> cbuffer=MemStreamData()
  >>> databuf = c_char * 100000
  >>> cbuffer.cpBuffer = POINTER(databuf)
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  TypeError: expected LP_c_char instance, got _ctypes.PointerType
  >>> databuftype = c_char * 100000
  >>> databuf = databuftype()
  >>> cbuffer.cpBuffer = databuf
  >>> databuf
  <__main__.c_char_Array_100000 object at 0xb7d04dac>

There is a shorthand for exactly this though as it is a common operation

  >>> databuf = create_string_buffer(1000)
  >>> cbuffer.cpBuffer = databuf
  >>> databuf
  <ctypes.c_char_Array_1000 object at 0xb7d129bc>


-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list