Author: Armin Rigo <[email protected]>
Branch:
Changeset: r2829:c23ad11dc403
Date: 2016-12-09 12:24 +0100
http://bitbucket.org/cffi/cffi/changeset/c23ad11dc403/
Log: Document 'FILE *'
diff --git a/doc/source/cdef.rst b/doc/source/cdef.rst
--- a/doc/source/cdef.rst
+++ b/doc/source/cdef.rst
@@ -183,9 +183,7 @@
* _Bool and bool (equivalent). If not directly supported by the C
compiler, this is declared with the size of ``unsigned char``.
-* FILE. You can declare C functions taking a ``FILE *`` argument and
- call them with a Python file object. If needed, you can also do
- ``c_f = ffi.cast("FILE *", fileobj)`` and then pass around ``c_f``.
+* FILE. `See here.`__
* all `common Windows types`_ are defined if you run
on Windows (``DWORD``, ``LPARAM``, etc.). Exception:
@@ -196,6 +194,7 @@
stdint.h, like ``intmax_t``, as long as they map to integers of 1,
2, 4 or 8 bytes. Larger integers are not supported.
+.. __: ref.html#file
.. _`common Windows types`:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
The declarations can also contain "``...``" at various places; these are
diff --git a/doc/source/ref.rst b/doc/source/ref.rst
--- a/doc/source/ref.rst
+++ b/doc/source/ref.rst
@@ -709,3 +709,35 @@
*New in version 1.7.* In previous versions, it only worked on
pointers; for primitives it always returned True.
+
+.. _file:
+
+Support for FILE
+++++++++++++++++
+
+You can declare C functions taking a ``FILE *`` argument and
+call them with a Python file object. If needed, you can also do ``c_f
+= ffi.cast("FILE *", fileobj)`` and then pass around ``c_f``.
+
+Note, however, that CFFI does this by a best-effort approach. If you
+need finer control over buffering, flushing, and timely closing of the
+``FILE *``, then you should not use this special support for ``FILE *``.
+Instead, you can handle regular ``FILE *`` cdata objects that you
+explicitly make using fdopen(), like this:
+
+.. code-block:: python
+
+ ffi.cdef('''
+ FILE *fdopen(int, const char *); // from the C <stdio.h>
+ int fclose(FILE *);
+ ''')
+
+ myfile.flush() # make sure the file is flushed
+ newfd = os.dup(myfile.fileno()) # make a copy of the file descriptor
+ fp = lib.fdopen(newfd, "w") # make a cdata 'FILE *' around newfd
+ lib.write_stuff_to_file(fp) # invoke the external function
+ lib.fclose(fp) # when you're done, close fp (and newfd)
+
+The special support for ``FILE *`` is anyway implemented in a similar manner
+on CPython 3.x and on PyPy, because these Python implementations' files are
+not natively based on ``FILE *``. Doing it explicity offers more control.
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit