gcc & python

报错

python 调用 dll 和 so 文件失败。
报错内容:OSError: [WinError 193] %1 不是有效的 Win32 应用程序

解决

生成的 dll 是32位,环境的 python 是64位。Anaconda 重新配置环境解决问题。

Anaconda 32位 python 环境配置

  1. 创建新的虚拟环境
  2. 切换到要修改的环境下
  3. 修改配置
    1
    2
    3
    set CONDA_FORCE_32BIT=1
    conda activate new_env_win32
    conda config --env --set subdir win-32

gcc使用

在桌面上创建一个 add.c 文件
文件内容如下所示:

1
2
3
4
5
6
7
8
#include <stdio.h>

int my_add(int a,int b)
{
int temp;
temp = a + b;
return temp;
}

然后打开cmd
切换到桌面目录

1
2
3
4
5
cd .\desktop
生成 so
gcc add.c -shared -o add.so
生成 dll
gcc add.c -shared -o add.dll

测试

1
2
3
4
5
6
7
8
9
10
from ctypes import cdll
from time import time

start = time()
dll = cdll.LoadLibrary('./add.dll')
so = cdll.LoadLibrary('./add.so')


print(dll.my_add(12, 33))
print(so.my_add(5, 5))

混合编程

更改 add.c 文件内容如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int my_add(int a,int b)
{
int temp;
temp = a + b;
return temp;
}

double db_add(double a,double b)
{
double temp;
temp = a + b;
return temp;
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import platform
from ctypes import *

if platform.system() == 'Windows':
libc = cdll.LoadLibrary('add.dll')
elif platform.system() == 'Linux':
libc = cdll.LoadLibrary('add.so')


# 指定 C 函数的参数类型
libc.my_add.argtypes = [c_int32, c_int32]
libc.db_add.argtypes = [c_double, c_double]
# 指定 C 函数的返回值类型
libc.my_add.restype = c_int32
libc.db_add.restype = c_double
print(libc.my_add(46, 46))
print(libc.db_add(90.123, 12.123))