【发布时间】:2016-02-16 08:56:21
【问题描述】:
我试图在python中使用c中的逻辑实现文件行计数程序。我编写了所需的C代码并在Linux中编译它以生成一个.so文件,它按预期顺利运行。
但是当我在 Windows 中编译它时,生成的 .dll 文件没有按预期工作。(我从 Cygwin 下载了我的 C 编译器)。
这是我的 C 代码:
#include <stdio.h>
#include <stdlib.h>
int counter(char file_name[]);
int counter(char file_name[]){
char ch;
FILE *fp;
int l=0;
fp = fopen(file_name,"r");
while( ( ch = fgetc(fp) ) != EOF )
{
if ((ch) == '\n')
{
l=l+1;
}
}
fclose(fp);
return l;
}
我把上面的代码编译成共享文件(.so/.dll)
下面是我的python代码:
from ctypes import *
#load the shared object file
myp = CDLL('./myp.so')
res_counter=myp.counter
i=raw_input("Enter File Path: ")
res_counter.restype=c_int
out=res_counter(i)
print out
在ubuntu中编译PFB
subbi@subbi-VirtualBox:~/Desktop/wctester/py2c$ ls
myp.c myp.so test2.py
subbi@subbi-VirtualBox:~/Desktop/wctester/py2c$ gcc -shared -o myp.so myp.c
/usr/bin/ld: /tmp/ccVAX8jf.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/tmp/ccVAX8jf.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
subbi@subbi-VirtualBox:~/Desktop/wctester/py2c$ gcc -shared -o myp.so -fPIC myp.c
subbi@subbi-VirtualBox:~/Desktop/wctester/py2c$ python test2.py
Enter File Path: ../bar
3
这是我的 windows 编译(我在 windows 的 .py 中将 myp.so 更改为 myp.dll)
[python2] C:\Users\Subbi Reddy\Desktop\py2c\py2c>ls
myp.c test2.py text.txt
[python2] C:\Users\Subbi Reddy\Desktop\py2c\py2c>gcc -shared -o myp.dll -fPIC my
p.c
myp.c:1:0: warning: -fPIC ignored for target (all code is position independent)
#include <stdio.h>
^
[python2] C:\Users\Subbi Reddy\Desktop\py2c\py2c>python test2.py
Enter File Path: text.txt
[python2] C:\Users\Subbi Reddy\Desktop\py2c\py2c>
窗口不显示结果(行数)
【问题讨论】:
-
您的程序以何种方式无法“按预期”运行?您需要举例说明您提供的输入和获得的输出。
-
你怎么知道它不起作用?
-
它显示什么?请明确点。有错误信息吗?它是否报告了一个错误的数字 - 太高或太低?
-
@barny 它没有在 Windows 中显示任何结果......如果你看到 linux 的输出它会在上面显示结果,那就是问题(3 是这种情况下的数字)跨度>
-
是当前目录下的文件text.txt吗?
标签: python c python-2.7 dll shared-libraries