# -*- coding: utf-8 -*-
import ctypes
from ctypes import *
import numpy as np
import sys
import struct
def demo_dll():
"""
调用C动态库中的函数
"""
mlibc = cdll.LoadLibrary('libutils.dll')
print ("begin")
n = mlibc.add(3, 4)
print (n)
print ("end")
return n
if __name__ == '__main__':
demo_dll()

其中 CDllForPython.dll 中的fnC函数,如下
int add(int a, int b)
{
printf("enter add\n");
return a + b;
}
在add中调用了printf.
在Python中调用add时,并没有按调用的先后顺序输出,实际输出顺序是
| 1 2 3 |
|
而期望的输出顺序是
begin
enter add
7
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.
下一步的工作就是把相应的缓存禁用掉. 或者 使用 cmd 控制台执行python脚本, 因使用pycharm会有打印顺序不一致问题
使用cmake-gui 和 mingw64 编译
python: https://blog.youkuaiyun.com/micorjun/article/month/2018/11
本文探讨了在Python中调用C动态库时遇到的输出顺序不一致问题,由于缓冲导致的实际输出与预期不符。解决方法包括禁用相关流的缓冲或通过CMD执行Python脚本。示例代码展示了如何加载并调用`libutils.dll`中的`add`函数,并给出了C函数的定义。文章还提到了使用cmake-gui和mingw64进行编译的相关信息。
1396





