[capi-sig] Python to Scheme type conversion in C?

Stefan Behnel stefan_ml at behnel.de
Mon May 31 21:05:30 CEST 2010

Jason Baker, 31.05.2010 18:15:
> I'm working on a Python-to-mzscheme binding using mzscheme's ffi
> library (mzscheme's rough equivalent of the Python ctypes library).
> I'm looking for a way to convert Python objects into Scheme values.
> Essentially what I'm trying to do is say "Is this a Python  integer?
> Ok, convert it to a Scheme integer."  or "Is this a Python string?
> Ok, convert it into a Scheme string."  ... etc.
> What is the best way to do this?  My first intuition was to call
> Py*_Check to determine the type, but it turns out that's a macro that
> can't be used in non-c code.  I'm sure I could translate that into the
> appropriate C code, but that gives me a bad feeling.

Those are macros because that makes them really, really fast, especially in 
Py3. However, their definition changes between Python versions, so 
replacing them by regular C code is really not a good idea.

In general, I wouldn't try to make the wrapper too generic. You might want 
to inspect the underlying Scheme code (potentially at runtime), and infer 
the possible types (or the required conversion) from that.

> Right now, I'm
> looking for simple and easy more than efficient and complete (but I
> would also like to know what the efficient and complete approach would
> be).

Have you considered integrating this with Cython via a thin C bridge, 
instead of talking to Python's C-API directly? Without knowing anything 
about the FFI you are using here, I suspect that it likely wouldn't be a 
generic wrapper in that case. Instead, it would allow users to write 
specialised and well optimised Scheme wrappers for their specific use case. 
So far, Cython supports calling into C, C++ and Fortran, where the Fortran 
wrapper is also implemented as a C-bridge (via fwrap). A similar Scheme 
binding would allow users to take advantage of Cython's static typing 
features, so that your code wouldn't have to guess types in the first place.


More information about the capi-sig mailing list