借鉴一下调用go的代码的基础环境gcc环境的那一部分
https://blog.csdn.net/wtt234/article/details/131155117?spm=1001.2014.3001.5501
一、C语言代码
pycall.c
#include <stdio.h>
#include <stdlib.h>
int foo(int a, int b)
{
printf("you input %d and %d\n", a, b);
return a+b;
}
/***gcc -o libpycall.so -shared -fPIC pycall.c*/
在命令行下用以下编译命令
gcc -o libpycall.so -shared -fPIC pycall.c
编译后直接生成 libpycall.so文件
然后复制到python目录下
二、python调用代码
from ctypes import cdll
if __name__ == '__main__':
libpycall=cdll.LoadLibrary("./libpycall.so")
ret2=libpycall.foo(10,10)
print(ret2)
三、测试代码
c语言代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int foo(int a, int b)
{
printf("you input %d and %d\n", a, b);
return a+b;
}
void printinfo(int a, char* b,char *buf)
{
printf("you input %d and %d\n", a, b);
sprintf(buf,"%d",a);
strcat(buf,b);
return ;
}
void printinttostr(int a, char str[25])
{
printf("you inputnew .... %d and %d\n", a, str);
itoa(a,str,10);
}
/***gcc -o libpycall.so -shared -fPIC pycall.c*/
py代码
from ctypes import cdll
if __name__ == '__main__':
libpycall=cdll.LoadLibrary("./libpycall.so")
ret2=libpycall.foo(10,10)
print(ret2)
print("=================")
# ret3=libpycall.printinfo(1,"2","")
# print(ret3,"<<<<<<,")
print("=================")
ret5=libpycall.printinttostr(1,"info999")
print(ret5)