Calling pcre with ctypes

Thomas Heller theller at python.net
Wed Jun 18 15:32:24 EDT 2008


moreati schrieb:
> Recently I discovered the re module doesn't support POSIX character
> classes:
> 
> Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import re
>>>> r = re.compile('[:alnum:]+')
>>>> print r.match('123')
> None
> 
> So I thought I'd try out pcre through ctypes, to recreate pcredemo.c
> in python. The c code is at:
> http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup
> 
> Partial Python code is below
> 
> I'm stuck, from what I can tell a c array, such as:
> int ovector[OVECCOUNT];
> 
> translates to
> ovector     = ctypes.c_int * OVECOUNT
> 
> but when I pass ovector to a function I get the traceback
> $ python pcredemo.py [a-z] fred
> Traceback (most recent call last):
>   File "pcredemo.py", line 65, in <module>
>     compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT
> ctypes.ArgumentError: argument 7: <type 'exceptions.TypeError'>: Don't
> know how to convert parameter 7
> 
> What is the correct way to construct and pass ovector?

'ctypes.c_int * OVECOUNT' does not create an array *instance*, it creates an array *type*,
comparable to a typedef in C.  You can create an array instance by calling the type, with
zero or more initializers:

ovector = (ctypes.c_int * OVECOUNT)(0, 1, 2, 3, ...)

Thomas



More information about the Python-list mailing list