可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):

问题:

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 );

Now; I would like to open file in python, and then use the Python file-object (in some way??) to get access to the underlying FILE * object and pass that to the C-function: # Python fileH = open( file , "r") value = ctypes_function_fread_int( ????? ) fileH.close()

Is the Python file FILE * mapping at all possible?

Joakim

回答1:

I've encountered the same problem.

Take a look at this file:

You can use PyFile_AsFile from it.

回答2:

A Python file object does not necessarily have an underlying C-level FILE * -- at least, not unless you're willing to tie your code to extremely specific Python versions and platforms.

What I would recommend instead is using the Python file object's fileno to get a file descriptor, then use ctypes to call the C runtime library's fdopen to make a FILE * out of that. This is a very portable approach (and you can go the other way, too). The big issue is that buffering will be separate for the two objects opened on the same file descriptor (the Python file object, and the C FILE *), so be sure to flush said objects as often as needed (or, open both as unbuffered, if that's more convenient and compatible with your intended use).

回答3:

Well;

I tried the fileno based solution, but was quite uncomfortable with opening the file twice; It was also not clear to me how to avoid the return value from fdopen() to leak.

In the end I wrote a microscopic C-extension: static PyObject cfile(PyObject * self, PyObject * args) { PyObject * pyfile; if (PyArg_ParseTuple( 'O' , &pyfile)) { FILE * cfile = PyFile_AsFile( pyfile ); return Py_BuildValue( "l" , cfile ); else return Py_BuildValue( "" ); }

which uses PyFile_AsFile and subsequently returns the FILE * pointer as a pure pointer value to Python which passes this back to C function expecting FILE * input. It works at least.

Joakim

回答4:

If you want to use stdout/stdin/stderr, you can import those variables from the standard C library. libc = ctypes.cdll.LoadLibrary('libc.so.6') cstdout = ctypes.c_void_p.in_dll(libc, 'stdout')

Or, if you want to avoid using void* for some reason: class FILE(ctypes.Structure): pass FILE_p = ctypes.POINTER(FILE) libc = ctypes.cdll.LoadLibrary('libc.so.6') cstdout = FILE_p.in_dll(libc, 'stdout')

回答5:

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)

回答6:

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.

python ctypes教程_Python ctypes: Python file object - C FILE * | 易学教程相关推荐

  1. python ctypes教程_python ctypes是什么

    ctypes是python的一个函数库,提供和C语言兼容的数据类型,可以直接调用动态链接库中的导出函数. 为了使用ctypes,必须依次完成以下步骤: ·加载动态链接库 ·将python对象转换成ct ...

  2. python ctypes 指针_Python Ctypes传递.h文件中定义的结构指针。

    我认为您可能缺少的是确切地知道您希望分配结构内存的位置.下面的c代码提供了一个为struct分配内存并返回指向它的指针的函数(new_struct()).#include #include #incl ...

  3. python json安装_Python JSON - Python 基础教程 - 自强学堂

    Python JSON 本章节我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象. Python 2.7 自带 JSON 模块[官方文档] 1. 从python原始类型向json ...

  4. python打地鼠游戏教程_Python入门小游戏,炫酷打地鼠教程第二部分,都是干货

    还记得那位玩打地鼠小游戏,然后学会python的女白领吗? 那份教程还没有写完,只写到了对游戏中精灵的定义,然后我们继续写. 实现了游戏精灵的定义后,我们就要开始展现真正的技术啦,也就是写主程序. 首 ...

  5. python 处理异常_Python异常处理– Python尝试除外

    python 处理异常 In our previous tutorial, we discussed about Python Directory. In this tutorial, we are ...

  6. c与python内存传递_python - 从Python向C ++传递COM指针数组 - 堆栈内存溢出

    我已经阅读了许多文档,示例和StackOverflow主题,但仍然无法正常工作! 我正在为我的C ++ COM对象编写一个Python接口. 这不是我第一次这样做. 过去,我已经成功地使用comtyp ...

  7. python解释器调用_python入门-python解释器执行

    最近由于公司需要,接触了python这门神奇的语言,给我的感觉就是开发快速和代码简洁. 开始还是先罗列一下解释性语言和编译性语言的差别吧0.0! 编译性语言:是在程序运行前,需要专门的一个编译过程,如 ...

  8. python冒泡排序函数_python冒泡排序-Python,冒泡排序

    arr = [ 7 , 4 , 3 , 67 , 34 , 1 , 8 ] . def bubble_sort : 最近在学习Python,下面是我的一些笔记 冒泡排序 实现思路: 使用双重for循环 ...

  9. python自动化入门_python自动化-python入门

    1.安装python,配置环境变量.windows下是安装路径直接配到环境变量里面就可以 mac添加环境变量 在~/.bash_profile这个文件中,添加一行 alias python=" ...

最新文章

  1. 机器视觉:工业线阵相机与面阵相机特点分析
  2. union all动态表_深入窥探动态链接
  3. DWZ与百度编辑器的IE8以下上传图片兼容问题
  4. 梯度与梯度下降法详解
  5. Linux内存管理:内存描述之内存页面page
  6. 计算机网络第二章-----物理层
  7. asp人脸识别,asp刷脸识别接口代码,微信公众号人脸识别代码
  8. VB串口通信技术资料:媒体/源码/论文/书籍/视频/控件/程序
  9. 我从不劝退,我就是退。
  10. 电机编码器调零步骤_伺服电机编码器调零
  11. android 国际区号注册手机号编码 以及常用城市列表
  12. 电商后台管理系统项目介绍和项目初始化
  13. 本地计算机 策略在哪xp系统,本地组策略编辑器在哪 打开组策略管理器方法
  14. ArcGIS中的 .tpk数据
  15. RTMP转HTTP-FLV视频流web端应用流程记录
  16. 对敏捷管理模式核心价值的解读
  17. 惠普HP Deskjet 1180c 打印机驱动
  18. 利用UE简化JAVA后端的SQL语句编辑
  19. 利用黑客手段一台手机“变”出千万台,新型诈骗技术曝光
  20. 达梦数据库-搭建DMHS双向同步

热门文章

  1. selenium自动化之鼠标操作
  2. Unity OBB分包(基础APK+OBB) 与apk签名
  3. 【codeforces 798A】Mike and palindrome
  4. 使用阿里云镜像maven管理配置开发环境
  5. POJ 2800 垂直直方图 解题报告
  6. js 层随着滚动条上下移动
  7. 美国版“健康码”遭遇尴尬:隐私保护最大化 疫情追踪基本无效
  8. 哪种Python IDE最适合你?这里有一份优缺点列表
  9. 沃尔沃投资两家以色列科技创企 布局人工智能
  10. 报告显示:2018年北京人工智能相关产业达1500亿元