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

前端 未结 6 772
深忆病人
深忆病人 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 05:07

    Adapted from svplayer

    import sys
    
    from ctypes import POINTER, Structure, py_object, pythonapi
    
    
    class File(Structure):
        pass
    
    if sys.version_info[0] > 2:
        convert_file = pythonapi.PyObject_AsFileDescriptor
        convert_file.restype = c_int
    else:
        convert_file = pythonapi.PyFile_AsFile
        convert_file.restype = POINTER(File)
    
    convert_file.argtypes = [py_object]
    
    fp = open('path').fp
    c_file = convert_file(fp)
    

提交回复
热议问题