[英]im trying to implement line count program in python with logic in c
我試圖用ci中的邏輯在python中實現文件行計數程序,我編寫了所需的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
PFB在Ubuntu中編譯
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>
窗口未顯示結果(行數)
我使用mingw32-gcc(4.7.1)編譯了您的代碼。 工作正常。
編輯:我也嘗試與cygwin。 它也在那里工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.