Carlos Pita | 6 Feb 15:25 2016

Structure inheritance and tail padding

Hi all,

just from observation I arrived to the unconfirmed conclusion that
Structure inheritance adds tail padding. For example:

class A(Structure):
  _fields_ = [('a', c_double), ('b', c_char)]

class B(A):
  _fields_ = [('c', c_int)]

will not show the same layout than:

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

Supposing my conclusion is right, what is the intention of this feature:

i. To support c++ pod subclassing? (most compilers reuse the tail
padding for non-pod subclassing).

ii. To support a more oo view of c struct composition? (btw, it
complements the ms-extensions very well).

Thank you in advance

Site24x7 APM Insight: Get Deep Visibility into Application Performance
(Continue reading)

Carlos Pita | 26 Jan 03:37 2016

resize content, not type

Hi all,

for the resize function the ctypes tutorial states:

> Another way to use variable-sized data types with ctypes is to use the dynamic
> nature of Python, and (re-)define the data type after the required size is already
> known, on a case by case basis.

What does this mean? I tried monkey-patching the __class__ attribute,
also changing the _length_ attribute, but to no avail. This is not
surprising as the relevant length attribute is part of the C-side
object state, which doesn't seem to be exposed to the python API and
won't change just because I changed the type after construction.

Another option is to resize and then create a new array from_address,
but it won't own the memory so it's a problematic approach.


Site24x7 APM Insight: Get Deep Visibility into Application Performance
APM + Mobile APM + RUM: Monitor 3 App instances at just $35/Month
Monitor end-to-end web transactions and take corrective actions now
Troubleshoot faster and improve end-user experience. Signup Now!
Andrew Robert Whalley | 21 Dec 13:48 2015

Library Import

Hi All,

I would like to use Python / ctypes to test a C library that contains 
some dependencies. Is it possible to satisfy those dependencies from 
within the Python interpreter, by using ctypes to define callables 
(similar to the callback function mechanism)? Or do any dependencies 
have to be defined in other, loadable, libraries?


Rob Whalley

Cristian Badescu | 28 Oct 13:31 2015



I am trying to get handles information by using NtQuerySystemInformation but my code fails for some reason. I am using the following code to call NtQuerySystemInformation:

from ctypes import *
from ctypes.util import *

class SYSTEM_HANDLE(Structure):

_fields_ = [("ProcessId", c_ulong),
("ObjetTypeNumber", c_byte),
("Flags", c_byte),
("Handle", c_ushort),
("Object", c_void_p ),
("GrantedAccess", c_ulong)


_fields_ = [("HandleCount", c_ulong),
("Handles", SYSTEM_HANDLE * 1)

handleInfoSize = 65536

SystemHandleInformation = 16

handleInfo = malloc(handleInfoSize)

pHandleInfo = cast(handleInfo, POINTER(SYSTEM_HANDLE_INFORMATION))

retVal = cdll.ntdll.NtQuerySystemInformation(SystemHandleInformation, pHandleInfo, handleInfoSize, None)
ctypes-users mailing list
ctypes-users <at>
TuX RaceR | 19 Aug 22:18 2015

Python ctypes program works on 3.2 but fails on 3.4

Hello List

I suspect a bug in ctypes;
I asked the question below on stackoverflow:

Any idea of why the same code would fail (return a blank string) on 3.4?


Jan Wagner | 13 Aug 07:19 2015

contribute ctypeslib patch?

Hi list, it seems this project is quite dead and I'm not sure how to contribute a feature fix (not even to Perhaps someone on the list is able to do it? There is an issue in ctypeslib that affects option "-r" for which usage says that "-r EXPRESSION regular expression for symbols to include". The expression is actually never evaluated as a regular expression. Only exact name matches are selected. The below patch changes the behaviour to be consistent with the usage instructions (and makes -r behaviour more useful). cheers, Jan --- /usr/lib/pymodules/python2.5/ctypeslib/codegen/ 2009-01-17 03:50:18.000000000 +0900 +++ 2015-04-08 18:34:06.000000000 +0900 <at> <at> -859,6 +859,12 <at> <at> if match and == todo.append(i) break + # above selects only *exact* matches, now include partial/regexp name matches: + match = + if match: + todo.append(i) + break + if symbols or expressions: items = todo
ctypes-users mailing list
ctypes-users <at>
Timothy W. Grove | 19 Mar 17:11 2015

Calling Objective C functions with ctypes

I have been trying to get the following code copied from another forum to work on my system (OSX 10.6, 10.8, Python 3.3 installed via MacPorts), and it just won't. It seems to be finding the 'AppKit' and 'objc' libraries okay, but it is not getting the classes 'NSSpeechSynthesizer' or 'NSAutoreleasePool', so 'count' ends up as '0' and everything falls over from there.

I did notice from the "print voiceNames" statement that this code must be pre-python 3, so are there any obvious changes needed to bring this up to date? Thanks for any help or suggestions.

Best regards,
Tim Grove
import ctypes
import ctypes.util

# Need to do this to load the NSSpeechSynthesizer class, which is in AppKit.framework
appkit = ctypes.cdll.LoadLibrary(ctypes.util.find_library('AppKit'))
objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))

objc.objc_getClass.restype = ctypes.c_void_p
objc.sel_registerName.restype = ctypes.c_void_p
objc.objc_msgSend.restype = ctypes.c_void_p
objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]

# Without this, it will still work, but it'll leak memory
NSAutoreleasePool = objc.objc_getClass('NSAutoreleasePool')
pool = objc.objc_msgSend(NSAutoreleasePool, objc.sel_registerName('alloc'))
pool = objc.objc_msgSend(pool, objc.sel_registerName('init'))

NSSpeechSynthesizer = objc.objc_getClass('NSSpeechSynthesizer')
availableVoices = objc.objc_msgSend(NSSpeechSynthesizer, objc.sel_registerName('availableVoices'))

count = objc.objc_msgSend(availableVoices, objc.sel_registerName('count'))
voiceNames = [
      objc.objc_msgSend(availableVoices, objc.sel_registerName('objectAtIndex:'), i),
  for i in range(count)]
print voiceNames

objc.objc_msgSend(pool, objc.sel_registerName('release'))
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now.
ctypes-users mailing list
ctypes-users <at>
狂禅 | 11 Mar 03:49 2015

who can tell me the difference in ctypes.sizeof between Ironpython and python in using ctypes to create structure?

recently i meet a problem in using Ironpython.
    import ctypes as ct
    class Data(ct.LittleEndianStructure):         
        _pack_      = 2
        _fields_    = [
    if __name__ == "__main__":
        a = Data()
        print ct.sizeof(a)
as is show above.when i used this script running in python ,it prints 12.
but when running in Ironpython ,it is 14.
in fact ,i tried it in c like that:

    void main()
    #pragma pack(2)
  unsigned char a;
  unsigned char b;
  unsigned char c;
  unsigned short d;
  unsigned int e;
  unsigned char f;
    #pragma pack()
it is 12.

can you tell me why it is and how i can crrect it in Ironpython???
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now.
ctypes-users mailing list
ctypes-users <at>
West, Peter | 30 Dec 18:15 2014



I need to pass a DLL a pointer to an array of pointers to c arrays of unsigned 16 bit integers.

I started to do this using data_as(POINTER( type ) on sub-arrays.  This caused access violations. When I
looked at what was in the pointer arrays I discovered that they all pointed to the same location.  After
poking around a bit is seems that the problem is not to do with using sub-arrays as I expected but with the way
in which I have approached the problem and I can't see what I'm doing wrong.  Here is a very simple example

from ctypes import POINTER, c_uint16
import numpy as  np

if __name__ == '__main__':

   pointerArrayType = POINTER( c_uint16 ) * 2      # an array of pointers type length 2
   pointers = pointerArrayType()                           # the actual array

   frame1 = np.zeros(( 100, 100 ), dtype = np.uint16, order = 'C' )   # Ensure C contiguous layout
   frame2 = np.zeros(( 100, 100 ), dtype = np.uint16, order = 'C' )

   pointers[ 0 ] = frame1.ctypes.data_as( POINTER( c_uint16 ))
   pointers[ 1 ] = frame2.ctypes.data_as( POINTER( c_uint16 ))

   print pointers[ 0 ]
   print pointers[ 1 ]

This prints 
<__main__.LP_c_ushort object at 0x00000000025132C8>
<__main__.LP_c_ushort object at 0x00000000025132C8>

This suggests that the data arrays for frame1 and frame2 are at the same location.  Clearly I've done
something wrong but can't see what.  

Any help would be gratefully received.
Dive into the World of Parallel Programming! The Go Parallel Website,
sponsored by Intel and developed in partnership with Slashdot Media, is your
hub for all things parallel software development, from weekly thought
leadership blogs to news, videos, case studies, tutorials and more. Take a
look and join the conversation now.
Koteswara Rao Ruvva | 22 Sep 07:34 2014

Array allocation

Hello All,

I have the following getData function in a DLL that allocates memory and fill its contents.

extern "C" __declspec(dllexport) int getData(int *data) {
int size = 20;
               data = (int*) malloc(size*sizeof(int));

for (int i = 0; i < size; i++) {
data[i] = i*i;

return size;

I have the following Python code to call the getData function:

       mydll = ctypes.cdll.Lo adLibrary('MathFuncs.dll')

       mydll.getData.argtypes = [ctypes.POINTER(ctypes.c_int)]
       mydll.getData.restype  = ctypes.c_int

       data = ctypes.POINTER(ctypes.c_int)
       size = mydll.getData(ctypes.POINTER(data))

When I execute, I get the following error:
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: expected LP_c_long instance instead of _ctypes.PyCPointerType

I am not able to figure out the mistake. Could someone please correct me.


Meet PCI DSS 3.0 Compliance Requirements with EventLog Analyzer
Achieve PCI DSS 3.0 Compliant Status with Out-of-the-box PCI DSS Reports
Are you Audit-Ready for PCI DSS 3.0 Compliance? Download White paper
Comply to PCI DSS 3.0 Requirement 10 and 11.5 with EventLog Analyzer
ctypes-users mailing list
ctypes-users <at>
Jason Marshall | 14 Jun 14:41 2014

ctypes.windll.kernel32.GetProcAddress returns address of 0

Hello ctypes-users,

I am a novice at ctypes and C. I am trying to get the addresses of some methods in ddraw.dll (obsolete, I know) so that I may use them with pygame. When I run the script below to get the methods' addresses, ctypes.windll.kernel32.GetProcAddress gives me addresses of 0. Can you see something that I'm doing wrong?

I have tried this in Python 2.7 (32-bit) under Win 7 (64-bit) and Python 2.5 (32-bit) under Win XP (32-bit). I got the same result in both environments.


# coding: cp1252
# What I am trying to do:
# DirectDrawCreate function
# IDirectDraw7::GetMonitorFrequency method
# IDirectDraw7::GetScanLine method
# DirectX headers
# scary GUID structure
# scary pointer to a pointer

import ctypes
from ctypes import POINTER, WINFUNCTYPE, byref, c_int, c_char_p, c_void_p, windll, wintypes

DD_OK = 0

# Load DirectDraw DLL
ddraw_dll = windll.LoadLibrary("ddraw")

# Initialize DirectDraw with DirectDrawCreate
class GUID(ctypes.Structure):
    _fields_ = [
        ('Data1', ctypes.c_ulong),
        ('Data2', ctypes.c_ushort),
        ('Data3', ctypes.c_ushort),
        ('Data4', ctypes.c_ubyte * 8)

    def __init__(self, l=0x6C14DB80, w1=0xA733, w2=0x11CE, b1=0xA5, b2=0x21, b3=0x00, b4=0x20, b5=0xAF, b6=0x0B, b7=0xE5, b8=0x60): # IID_IDirectDraw
        self.Data1 = l
        self.Data2 = w1
        self.Data3 = w2
        self.Data4[:] = (b1, b2, b3, b4, b5, b6, b7, b8)

    def __repr__(self):
        b1, b2, b3, b4, b5, b6, b7, b8 = self.Data4
        return 'GUID(%x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x)' % (
            self.Data1, self.Data2, self.Data3, b1, b2, b3, b4, b5, b6, b7, b8)

DirectDrawCreate = ddraw_dll.DirectDrawCreate
DirectDrawCreate.argtypes = [c_void_p, POINTER(POINTER(GUID)), c_void_p]
control = POINTER(GUID)()
result = DirectDrawCreate(None, byref(control), None)

print "DirectDrawCreate result (0 is DD_OK):", result
assert result == DD_OK, "DirectDraw did not initialize"

# Get GetMonitorFrequency function's address
windll.kernel32.GetProcAddress.argtypes = [c_void_p, c_char_p]
GetMonitorFrequency_addr = windll.kernel32.GetProcAddress(ddraw_dll._handle, "GetMonitorFrequency")
print "GetMonitorFrequency_addr", hex(GetMonitorFrequency_addr)

# Get GetScanLine function's address
GetScanLine_addr = windll.kernel32.GetProcAddress(ddraw_dll._handle, "GetScanLine")
print "GetScanLine_addr", hex(GetScanLine_addr)

HPCC Systems Open Source Big Data Platform from LexisNexis Risk Solutions
Find What Matters Most in Your Big Data with HPCC Systems
Open Source. Fast. Scalable. Simple. Ideal for Dirty Data.
Leverages Graph Analysis for Fast Processing & Easy Data Exploration
ctypes-users mailing list
ctypes-users <at>