python调用c语言代码

借鉴一下调用go的代码的基础环境gcc环境的那一部分

(599条消息) python调用go语言的代码_雨师@的博客-CSDN博客

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值