在Python中使用C函数
我尝试在Python中使用以下C函数:在Python中使用C函数,python,c,function,script,Python,C,Function,Script,我尝试在Python中使用以下C函数: /*scp.c : prints its input with a space after each letter*/ #include <stdio.h> #define MSTACK 5000 void spc(int, int); int main(void){ int c; spc(c, MSTACK); return 0; } void spc(int c, int lim){ int i;
/*scp.c : prints its input with a space after each letter*/
#include <stdio.h>
#define MSTACK 5000
void spc(int, int);
int main(void){
int c;
spc(c, MSTACK);
return 0;
}
void spc(int c, int lim){
int i;
for(i = 0; i < lim-- && (c = getchar()) != EOF && c != '\n'; i++){
putchar(c);
putchar(' ');
}
}
spc()接受一个整数,由getchar()使用,另一个整数表示可能输入的限制。
既然intc
是直接从main使用的输入本身,那么我可以在python脚本中传递什么
space = spc.spc()
不确定为什么在共享对象中有一个main函数,特别是如果它不是从python脚本调用的。我在测试中删除了它 使用
ctypes
调用函数时,必须声明被调用函数的输入参数和返回类型
from ctypes import *
spc = CDLL('./spc.so')
spec = spc.spc
spec.restype = None
spec.argtypes = [c_int, c_int]
spec(3, 5000)
#include <stdio.h>
#define MSTACK 5000
void spc(void);
void spc(void){
int i;
int c;
int lim = MSTACK;
for(i = 0; i < lim-- && (c = getchar()) != EOF && c != '\n'; i++){
putchar(c);
putchar(' ');
}
}
如果lim
始终是MSTACK
,则函数也不需要输入参数c
作为输入参数没有意义,只需在函数中声明即可
from ctypes import *
spc = CDLL('./spc.so')
spec = spc.spc
spec.restype = None
spec.argtypes = [c_int, c_int]
spec(3, 5000)
#include <stdio.h>
#define MSTACK 5000
void spc(void);
void spc(void){
int i;
int c;
int lim = MSTACK;
for(i = 0; i < lim-- && (c = getchar()) != EOF && c != '\n'; i++){
putchar(c);
putchar(' ');
}
}
您的
spc
函数不返回任何内容,需要2个整数参数(第一个参数完全忽略)。为什么不传递2个整数参数?(另外,主函数将未初始化的变量作为第一个参数传递给spc
。