|
22 | 22 | File Paths and Files
|
23 | 23 | **********************
|
24 | 24 |
|
25 |
| -This chapter describes reading and writing files from CPython extensions. |
| 25 | +This chapter describes reading and writing files from CPython C extensions. |
26 | 26 |
|
27 | 27 | .. index::
|
28 | 28 | single: File Paths
|
@@ -57,6 +57,7 @@ In summary:
|
57 | 57 | - `PyUnicode_EncodeFSDefault()`_ Takes a Python ``str`` and return a Python ``bytes`` object.
|
58 | 58 |
|
59 | 59 | The example code is in:
|
| 60 | + |
60 | 61 | - ``src/cpy/cFile.cpp``
|
61 | 62 | - ``src/cpy/PythonFileWrapper.h``
|
62 | 63 | - ``src/cpy/PythonFileWrapper.cpp``
|
@@ -308,8 +309,7 @@ A C++ Python File Wrapper
|
308 | 309 |
|
309 | 310 | In ``src/cpy/PythonFileWrapper.h`` and ``src/cpy/PythonFileWrapper.cpp`` there is a C++ class that takes a Python file
|
310 | 311 | and extracts the ``read()``, ``write()``, ``seek()`` and ``tell()`` methods that can then be used to read and write to
|
311 |
| -the Python file from C++. Some example code is in ``src/cpy/cFile.cpp`` and some tests are in |
312 |
| -``tests/unit/test_c_file.py``. |
| 312 | +the Python file from C++. |
313 | 313 |
|
314 | 314 | Here is the class:
|
315 | 315 |
|
@@ -363,4 +363,43 @@ Here is the class:
|
363 | 363 | PyObject *m_python_tell_method = NULL;
|
364 | 364 | };
|
365 | 365 |
|
| 366 | +Some example code is in ``src/cpy/cFile.cpp``: |
| 367 | + |
| 368 | +.. code-block:: cpp |
| 369 | +
|
| 370 | + /** |
| 371 | + * Wraps a Python file object. |
| 372 | + */ |
| 373 | + static PyObject * |
| 374 | + wrap_python_file(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) { |
| 375 | + assert(!PyErr_Occurred()); |
| 376 | + static const char *kwlist[] = {"file_object", NULL}; |
| 377 | + PyObject *py_file_object = NULL; |
| 378 | +
|
| 379 | + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", (char **) (kwlist), |
| 380 | + &py_file_object)) { |
| 381 | + return NULL; |
| 382 | + } |
| 383 | + PythonFileObjectWrapper py_file_wrapper(py_file_object); |
| 384 | +
|
| 385 | + /* Exercise ths wrapper by writing, reading etc. */ |
| 386 | + py_file_wrapper.write("Test write to python file", 25); |
| 387 | + return py_file_wrapper.py_str_pointers(); |
| 388 | + } |
366 | 389 |
|
| 390 | +And some tests are in ``tests/unit/test_c_file.py``: |
| 391 | + |
| 392 | +.. code-block:: python |
| 393 | +
|
| 394 | + def test_wrap_python_file(): |
| 395 | + file = io.BytesIO() |
| 396 | + result = cFile.wrap_python_file(file) |
| 397 | + print() |
| 398 | + print(' Result '.center(75, '-')) |
| 399 | + print(result.decode('ascii')) |
| 400 | + print(' Result DONE '.center(75, '-')) |
| 401 | + print(' file.getvalue() '.center(75, '-')) |
| 402 | + get_value = file.getvalue() |
| 403 | + print(get_value) |
| 404 | + print(' file.getvalue() DONE '.center(75, '-')) |
| 405 | + assert get_value == b'Test write to python file' |
0 commit comments