Calling Python macro from ctypes

Steven D'Aprano steve at pearwood.info
Tue Aug 13 05:13:52 EDT 2013


On Tue, 13 Aug 2013 10:11:29 +0200, Stefan Behnel wrote:

> Steven D'Aprano, 13.08.2013 08:25:
>> On Mon, 12 Aug 2013 13:42:14 +0200, Peter Otten wrote:
>>> Steven D'Aprano wrote:
>>>
>>>> Is it possible to call a Python macro from ctypes? For example,
>>>> Python 3.3 introduces some new macros for querying the internal
>>>> representation of strings:
>>>>
>>>> http://www.python.org/dev/peps/pep-0393/#new-api
>> [...]
>> 
>>> That's not possible. It may look like a function, but a preprocessor
>>> replaces the C macro in the C source before compilation.
>> 
>> That's what I feared.
>> 
>> In that case, how would I use ctypes to access the underlying fields in
>> the new string implementation?
> 
> I'd personally use Cython (no surprise here), but in order to use
> something like ctypes, which works at the ABI level, not the API level,
> and doesn't use a C compiler to get things properly configured for the
> local platform, you'd have to manually define the actual PyObject struct
> in order to access its fields directly.
> 
> The macros are there to give you source code level portability for that,
> but if you start defining the struct layout statically, you're pretty
> much on your own when it comes to stuff like different CPython versions,
> debug builds, etc.
> 
> Could you describe your use case a little deeper? Maybe there's a better
> way all together to do what you want.

One concrete example of what I want to do is introspect Python 3.3 
strings. E.g. to tell whether they are 1 byte, 2 byte or 4 byte strings. 
Strings have a "kind" field, set to 0-3, that specifies how many bytes 
per char, but it is not exposed to Python.



-- 
Steven



More information about the Python-list mailing list