2015-05-20 9:54 GMT+02:00 Yicong Huang <[email protected]>: > Yes, C could *not* have a function that returns either a double or NULL. > But python could. > In addition, python could have a function paramter that is either int or > None. > > The problem is we might get a python function, and we would like to call > this python function in C. > We're not sure whether this function return int or return None. > Follow the document ,we might define the function callback as below: > @ffi.callback("int (int, int)") > However, sometimes the python function will return None, which cause > Operation Error from CFFI. > > On the other hand, it is valid to python for receving the function > parameter as None. > How could we pass NULL to python function via ffi.callback definition? >
cffi basic usage is to call C functions from Python, and is was designed for this. C is a simple language. Your use case is the opposite: call Python from C, and it's going to be more complex because Python types are way more flexible than C. To call from C a Python function that can return multiple types, you will have to design (in C) some way to embed these types in a single value, and more code to manipulate this value. For example, the CPython API uses the PyObject* type to represent anything, and has more than 400 functions like PyFloat_AsDouble. Yes, this is involved: cffi.new_handle() can be used to return any Python object to C, but the handle needs to stay alive on the Python side, so a pool of returned handles is necessary, but it needs to be cleared sometimes, and there will be many helper functions... I once wrote some code to demonstrate this, I need to clean it a bit and put it in the docs. -- Amaury Forgeot d'Arc
_______________________________________________ pypy-dev mailing list [email protected] https://mail.python.org/mailman/listinfo/pypy-dev
