Python和C语⾔的混合编程【windows系统】
ctypes是python标准库的⼀员,相当于为python与C语⾔之间假设了⼀道桥梁,使得⼆者之间的混合编程成为可能。
例如我们⽤C语⾔写⼀个希尔排序
//sort.h
#include<stdio.h>
void ShellSort(double*arr,int n);
//sort.c
#include"sort.h"
void ShellSort(double*arr,int n){
double temp;
int j;
for(int nSub=n/2; nSub>0; nSub/=2)
for(int i=nSub; i<n; i++){
temp = arr[i];
for(j=i-nSub;  j>=0&& temp<arr[j]; j-=nSub)
arr[j+nSub]= arr[j];
arr[j+nSub]= temp;
}
}
先写⼀个test.c做测试。
//test.c
#include"sort.h"
int main(){
double arr[5]={1,3,5,4,2};
c语言和c++区别ShellSort(arr,5);
for(int i=0; i<5; i++)
printf("%lf ", arr[i]);
return0;
}
⾸先通过gcc -shared -o将sort.c变成sort.dll,再将sort.dll链接到test.c中,从⽽⽣成。gcc会⾃动将-l后⾯的sort识别为sort.dll。
>gcc -shared -o sort.dll sort.c
>gcc - .\test.c -L./ -lsort
&
1.000000
2.000000
3.000000
4.000000
5.000000
<成功运⾏,说明我们这个函数是正确的。
接下来需要在python中通过ctypes进⾏调⽤。务必注意python和dll须有相同的数据位数。在windows下,如果⽤mingw中的gcc,只能编译32位程序,⽽若Python为64位,则会报出如下错误
>>>import ctypes
>>> dll = ctypes.CDLL("./sort.dll")
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
File "C:\Python310\lib\ctypes\__init__.py", line 374,in __init__
self._handle = _dlopen(self._name, mode)
OSError:[WinError 193]%1不是有效的 Win32 应⽤程序。
为了解决这个问题,需要下载安装。
在正确安装并设置mingw-w64之后,进⼊python
>>>import ctypes
>>> dll = ctypes.CDLL("./sort.dll")
>>> tenValues = ctypes.c_double *10#新建⼀个长度位10的double型数组>>> v = tenValues(1,3,5,7,9,8,6,4,2,10)
>>> dll.ShellSort(v,10)
>>>for i in v:print(i,end=' ')
...
1.02.03.04.05.06.07.08.09.010.0
可见希尔排序的确起到了作⽤。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。