【问题标题】:im trying to implement line count program in python with logic in c我试图用c中的逻辑在python中实现行数程序
【发布时间】: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


【解决方案1】:

我使用 mingw32-gcc(4.7.1) 编译了您的代码。它工作正常。

编辑: 我也试过用cygwin。它也可以在那里工作。

【讨论】:

  • 编译对我有用...它是否也为您发布了行数?(即结果)
  • @Subbireddydwarampudi 是的。我做了完全相同的步骤,得到了行数。
  • 我从 cygwin 下载了我的 gcc 编译器...但我不确定我做错了什么还是 cygwin 有问题。
  • @Subbireddydwarampudi 尝试 mingw(更容易安装代码块)。要检查 cygwin 问题,请尝试使用 c 代码中的 dll。
猜你喜欢
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 2018-09-25
  • 2017-01-20
  • 1970-01-01
相关资源
最近更新 更多