python和C++调用动态库
python和C++相互调用动态库的方法有4种:
- python调用C/C++编译的动态库
- python调用python编译的动态库
- C/C++调用python编译的动态库
- C/C++调用C/C++编译的动态库
python调用C/C++编译的动态库
mean.c
#include "mean.h"
double mean(double a, double b) {
return (a+b)/2;
}
mean.h
// Returns the mean of passed parameters
double mean(double, double);
C/C++代码编译
gcc -shared -o libmean.so.1 mean.c
python调用
import ctypes
libmean = ctypes.CDLL("libmean.so.1") # loads the shared library
libmean.mean.restype = ctypes.c_double # define mean function return type
# 方法一
libmean.mean(ctypes.c_double(10), ctypes.c_double(3)) # call mean function needs cast arg types
# 6.5
# 方法二(推荐)
libmean.mean.argtypes = [ctypes.c_double, ctypes.c_double] # define arguments types
libmean.mean(10, 3) # call mean function does not need cast arg types
# 6.5
type(libmean.mean(10, 5)) # returned value is converted to python types
# <type 'float'>
类型映射表
python调用python编译的动态库
python编译出动态库方法,setup.py方法
val.py
import os
def i_sum(a, b):
# 计算两数之和
c = a + b
return c
setup.py
# pip install cpython
from distutils.core import setup
from Cython.Build import cythonize
# 如果有多个python文件在列表中添加
setup(ext_modules=cythonize(["val.py"]))
python编译
在setup.py同级路径,会生成val.cpython-38-x86_64-linux-gnu.so
python调用python编译生成的动态库一定不能改动态库名字
python setup.py build_ext --inplace
python调用
import val
a = 10
b = 2
print(val.i_sum(a,b))
# 12