首页 > 编程知识 正文

python如何调用c语言程序,c怎么调用python

时间:2023-12-27 22:26:51 阅读:325020 作者:BNPD

本文目录一览:

如何在python中调用C语言代码

先把C语言代码做成DLL文件,再用python加载此DLL文件来访问C语言功能代码

如何让python调用C和C++代码

二、Python调用C/C++1、Python调用C动态链接库Python调用C库比较简单,不经过任何封装打包成so,再使用python的ctypes调用即可。(1)C语言文件:pycall.c[html]viewplaincopy/***gcc-olibpycall.so-shared-fPICpycall.c*/#include#includeintfoo(inta,intb){printf("youinput%dand%dn",a,b);returna+b;}(2)gcc编译生成动态库libpycall.so:gcc-olibpycall.so-shared-fPICpycall.c。使用g++编译生成C动态库的代码中的函数或者方法时,需要使用extern"C"来进行编译。(3)Python调用动态库的文件:pycall.py[html]viewplaincopyimportctypesll=ctypes.cdll.LoadLibrarylib=ll("./libpycall.so")lib.foo(1,3)print'***finish***'(4)运行结果:2、Python调用C++(类)动态链接库需要extern"C"来辅助,也就是说还是只能调用C函数,不能直接调用方法,但是能解析C++方法。不是用extern"C",构建后的动态链接库没有这些函数的符号表。(1)C++类文件:pycallclass.cpp[html]viewplaincopy#includeusingnamespacestd;classTestLib{public:voiddisplay();voiddisplay(inta);};voidTestLib::display(){cout#include#includeintfac(intn){if(n2)return(1);/*0!==1!==1*/return(n)*fac(n-1);/*n!==n*(n-1)!*/}char*reverse(char*s){registerchart,/*tmp*/*p=s,/*fwd*/*q=(s+(strlen(s)-1));/*bwd*/while(p

python 怎么调用c语言接口

ctypes:  可直接调用c语言动态链接库。

使用步骤:

1 编译好自己的动态连接库

2 利用ctypes载入动态连接库

3 用ctype调用C函数接口时,需要将python变量类型做转换后才能作为函数参数,转换原则见下图:

4 Python若想获取ctypes调用的C函数返回值,需要先指定返回值类型。我们将在接下来的完整Sample中看到如何使用。

#Step 1:  test.c#include stdio.h

int add(int a, int b)

{

    return a + b;

}#Step 2: 编译动态链接库 ( 如何编译动态链接库在本文不详解,网上资料一大堆。)gcc -fPIC -shared test.c -o libtest.so  

#Step 3:  test.py

from ctypes import *mylib = CDLL("libtest.so")   或者   cdll.LoadLibrary("libtest.so")   add = mylib.add

add.argtypes = [c_int, c_int] # 参数类型,两个int(c_int是ctypes类型,见上表)

add.restype = c_int # 返回值类型,int (c_int 是ctypes类型,见上表)

sum = add(3, 6)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。