用 Cygwin 编译并从 Python 调用的 C 程序挂起
C Program Compiled with Cygwin and Called from Python Hangs
我正在尝试使用 ctypes
从 Python 调用一个 c 程序。我在下面有一个最小的(非)工作示例。
C 程序
这是我要调用的 C 程序。只是您的标准 hello world 程序。我在 windows 上编译它,使用 eclipse 和 cygwin gcc 编译器生成一个 .dll
文件。
main.h
#ifndef INC_MAIN_H_
#define INC_MAIN_H_
void helloWorld();
unsigned char buf[] = "Hello World!";
#endif /* INC_MAIN_H_ */
main.c
#include <stdio.h>
#include "main.h"
void helloWorld(){
printf("\n%s\n\n", buf);
}
Python 计划
然后我编写一个 python 脚本来加载我的 .dll
并调用 helloWorld
函数。重要的是,我确实把我创建的 .dll
和 cygwin1.dll
.
helloWorld.py
from ctypes import CDLL
import os
def loadDLL(file):
file = file.replace('\','/')
if not os.path.exists(file):
raise FileNotFoundError(file)
print('Opening DLL File:', file)
dll = CDLL(file)
return dll
if __name__ == '__main__':
dll = loadDLL(FILE_TO_LOAD)
dll.helloWorld()
当我转到 运行 这个程序时,loadDLL
工作正常并加载了 DLL。但是,从 c 程序调用 helloWorld
函数会导致它挂起。
奇怪的是,如果我用无害的东西(例如,int x = 0
)替换 printf
行,它执行得很好,但打印出一个看似随机的数字。
谁能指出我做错了什么?或者甚至是找出问题所在的方法?
顺便说一句,我能够获得几乎相同的设置,以便在 linux 系统上正常工作,所以我猜这是由于我设置的 windows 环境,但我无法开始猜测它到底是什么。
更新
我写这个不是作为答案,因为它不能解决问题的字面意思,而只能解决问题的精神。
在 I dropped cygwin for mingw and things now work as expected. Apparently cygwin works in strange ways. was able to find a useful link 关于如果要将 cygwin 程序用于外部库应该如何编译,但这似乎比使用 mingw 麻烦得多(更不用说我想的其他问题了已经遇到过尝试为此使用 cygwin)。
FWIW,此程序还必须 运行 在命令行中才能看到 c 程序的输出。 python 的 IDLE 中的 运行 没有捕获 c 程序的 printf
输出。
问题是您从 NOT cygwin python 调用 cywgin 程序并且有错误的期望。
cygwin 程序与普通 windows 程序具有不同的范例(Posix 类)。
建议同时使用cygwin python 和编译器进行测试,或者同时使用windows 两者。
我正在尝试使用 ctypes
从 Python 调用一个 c 程序。我在下面有一个最小的(非)工作示例。
C 程序
这是我要调用的 C 程序。只是您的标准 hello world 程序。我在 windows 上编译它,使用 eclipse 和 cygwin gcc 编译器生成一个 .dll
文件。
main.h
#ifndef INC_MAIN_H_
#define INC_MAIN_H_
void helloWorld();
unsigned char buf[] = "Hello World!";
#endif /* INC_MAIN_H_ */
main.c
#include <stdio.h>
#include "main.h"
void helloWorld(){
printf("\n%s\n\n", buf);
}
Python 计划
然后我编写一个 python 脚本来加载我的 .dll
并调用 helloWorld
函数。重要的是,我确实把我创建的 .dll
和 cygwin1.dll
.
helloWorld.py
from ctypes import CDLL
import os
def loadDLL(file):
file = file.replace('\','/')
if not os.path.exists(file):
raise FileNotFoundError(file)
print('Opening DLL File:', file)
dll = CDLL(file)
return dll
if __name__ == '__main__':
dll = loadDLL(FILE_TO_LOAD)
dll.helloWorld()
当我转到 运行 这个程序时,loadDLL
工作正常并加载了 DLL。但是,从 c 程序调用 helloWorld
函数会导致它挂起。
奇怪的是,如果我用无害的东西(例如,int x = 0
)替换 printf
行,它执行得很好,但打印出一个看似随机的数字。
谁能指出我做错了什么?或者甚至是找出问题所在的方法?
顺便说一句,我能够获得几乎相同的设置,以便在 linux 系统上正常工作,所以我猜这是由于我设置的 windows 环境,但我无法开始猜测它到底是什么。
更新
我写这个不是作为答案,因为它不能解决问题的字面意思,而只能解决问题的精神。
在
FWIW,此程序还必须 运行 在命令行中才能看到 c 程序的输出。 python 的 IDLE 中的 运行 没有捕获 c 程序的 printf
输出。
问题是您从 NOT cygwin python 调用 cywgin 程序并且有错误的期望。
cygwin 程序与普通 windows 程序具有不同的范例(Posix 类)。
建议同时使用cygwin python 和编译器进行测试,或者同时使用windows 两者。