Python ctypes: Python file object <-> C FILE *

前端 未结 6 774
深忆病人
深忆病人 2020-12-14 04:16

I am using ctypes to wrap a C-library (which I have control over) with Python. I want to wrap a C-function with declaration:

int fread_int( FILE * stream );
         


        
6条回答
  •  盖世英雄少女心
    2020-12-14 04:50

    Tried this:

    #if PY_MAJOR_VERSION >= 3
        if (PyObject_HasAttrString(pyfile, "fileno")) {
            int fd = (int)PyLong_AsLong(PyObject_CallMethod(pyfile, "fileno", NULL));
            if (PyObject_HasAttrString(pyfile, "mode")) {
                char *mode = PyUnicode_AsUTF8AndSize(
                        PyObject_CallMethod(pyfile, "mode", NULL), NULL);
                fp = fdopen(fd, mode);
            }
            else {
                return PyErr_Format(PyExc_ValueError,
                        "File doesn’t have mode attribute!");
            }
        }
        else {
            return PyErr_Format(PyExc_ValueError,
                    "File doesn’t have fileno method!");
        }
    #else
        fp = PyFile_AsFile(pyfile);
    #endif
    

    It looks like it might be working.

提交回复
热议问题