File: fileshim.h

package info (click to toggle)
pyhst2 2020c-7
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm, sid
  • size: 13,540 kB
  • sloc: ansic: 11,807; python: 9,708; cpp: 6,786; makefile: 152; sh: 31
file content (49 lines) | stat: -rw-r--r-- 1,127 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* Copyright (c) 2015, Red Hat, Inc. and/or its affiliates
 * Licensed under the MIT license; see py3c.h
 */

#ifndef _PY3C_FILESHIM_H_
#define _PY3C_FILESHIM_H_
#include <Python.h>

/*

For debugging purposes only.
Caveats:
 * Only works on file-like objects backed by an actual file
 * All C-level writes should be done before additional
   Python-level writes are allowed (e.g. by running Python code).
 * Though the function tries to flush, there is no guarantee that
   writes will be reordered due to different layers of buffering.

*/

static char FLUSH[] = "flush";
static char EMPTY_STRING[] = "";

static FILE* py3c_PyFile_AsFileWithMode(PyObject *py_file, const char *mode) {
    FILE *f;
    PyObject *ret;
    int fd;

    ret = PyObject_CallMethod(py_file, FLUSH, EMPTY_STRING);
    if (ret == NULL) {
        return NULL;
    }
    Py_DECREF(ret);

    fd = PyObject_AsFileDescriptor(py_file);
    if (fd == -1) {
        return NULL;
    }

        f = fdopen(fd, mode);
    if (f == NULL) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }

    return f;
}

#endif /* _PY3C_FILESHIM_H_ */