Issue #101 wontfix

Generalized coersion for arbitrary objects?

Isaac Freeman
created an issue

It would be nice if there was a way for a user-defined class to tell CFFI how to coerce/convert the object in to a compatible type. For some types this is pretty simple already, i.e., defining an __int__ method or something, but for types like structs/etc there doesn't seem to be a straightforward way to do this.

A simple solution I think would be to see if the object has a _cdata attribute and use that as the data to be passed in to the C function.

For example:

class MyStruct:
    def __init__(self, x, y):
        self._cdata = my_ffi.create_mystruct(x, y)

And/or maybe a _to_cdata method for objects that need to compute a compatible type.

class MyStruct2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def _to_cdata(self):
        return {'x': self.x, 'y': self.y}

And then recursively coerce the return value.

If others like this idea, I might be able to submit a pull request with a basic implementation of this.

Comments (4)

  1. Armin Rigo

    The basic design idea of CFFI is that it gives you the "raw" access, and then you add some wrappers in pure Python around it with whatever convention you choose for your program. So I don't like the idea of CFFI calling _to_cdata() automatically: you might as well call it yourself in the wrappers. (This is a difference with ctypes: keep CFFI more minimal.)

  2. Isaac Freeman reporter

    I understand the desire to keep CFFI minimal, but one of the biggest strengths of python is it's introspection and overloading abilities, so I thought it would be a great idea for CFFI.

    Anyways, fair enough, I don't mind adding it to my own wrapper code (in fact, I already have as a work-around). I just thought maybe others would find it useful.

  3. Log in to comment