Python 中调用C DLL printf 输出顺序的问题研究
Python中有段代码
1 # -*- coding: utf-8 -*- 2 import ctypes 3 from ctypes import windll 4 5 6 def callc(): 7 """ 8 调用C动态库中的函数 9 """ 10 somelibc = windll.LoadLibrary(r"C:\...\CDllForPython.dll") 11 print ("Start") 12 n = somelibc.fnC() 13 print (n) 14 print ("End") 15 return n 16 17 18 if __name__ == '__main__': 19 callc()
其中 CDllForPython.dll 中的fnC函数,如下
1 CDLL_API int fnC() 2 { 3 printf("temp"); 4 return sizeof(int) * 123; 5 }
在fuC中调用了printf.
在Python中调用fnC时,并没有按调用的先后顺序输出,实际输出顺序是
Start 492 End
temp
而期望的输出顺序是
Start temp 492 End
在https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/上有说明
The output order may not be what we expected. This is due to buffering. If it's important to preserve order between different kinds of output (i.e. between C and Python), further work is required to disable buffering on all relevant streams.
下一步的工作就是把相应的缓存禁用掉.
浙公网安备 33010602011771号