python調(diào)用C/C++動(dòng)態(tài)庫(kù)的實(shí)踐案例
前言
Python通過(guò)ctypes模塊可以方便地調(diào)用C/C++編寫的動(dòng)態(tài)庫(kù)(Windows下為DLL,Linux下為SO文件)。這種方式允許Python與底層系統(tǒng)進(jìn)行高效交互,廣泛用于硬件控制、高性能計(jì)算等場(chǎng)景。
基本原理
- 動(dòng)態(tài)庫(kù)加載:使用
ctypes.CDLL(加載C庫(kù))或ctypes.WinDLL(加載Windows特定的stdcall調(diào)用約定的DLL)加載動(dòng)態(tài)庫(kù)文件 - 函數(shù)參數(shù)與返回值類型聲明:明確指定C函數(shù)的參數(shù)類型和返回值類型,確保數(shù)據(jù)傳遞正確
- 數(shù)據(jù)類型映射:將Python數(shù)據(jù)類型轉(zhuǎn)換為C兼容的數(shù)據(jù)類型(如整數(shù)、字符串、結(jié)構(gòu)體等)
實(shí)踐案例
1. 簡(jiǎn)單C函數(shù)調(diào)用示例
C代碼(保存為example.c):
// example.c
#include <stdio.h>
// 簡(jiǎn)單加法函數(shù)
int add(int a, int b) {
return a + b;
}
// 字符串處理函數(shù)
void reverse_string(char* str) {
int len = 0;
while (str[len] != '\0') len++;
for (int i = 0; i < len/2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
編譯為動(dòng)態(tài)庫(kù):
# Linux/macOS gcc -shared -o example.so -fPIC example.c # Windows (MinGW) gcc -shared -o example.dll example.c
Python調(diào)用代碼:
import ctypes
# 加載動(dòng)態(tài)庫(kù)
lib = ctypes.CDLL('./example.so') # Linux/macOS
# lib = ctypes.CDLL('./example.dll') # Windows
# 調(diào)用add函數(shù)
add_result = lib.add(3, 4)
print(f"3 + 4 = {add_result}") # 輸出: 7
# 調(diào)用reverse_string函數(shù)
# 注意:需要傳遞可變的字節(jié)數(shù)組
s = ctypes.create_string_buffer(b"hello")
lib.reverse_string(s)
print(f"Reversed: {s.value.decode()}") # 輸出: olleh

2. 傳遞和返回結(jié)構(gòu)體
C代碼(保存為struct_example.c):
#include <stdio.h>
// 定義結(jié)構(gòu)體
typedef struct {
int x;
int y;
} Point;
// 結(jié)構(gòu)體加法函數(shù)
Point add_points(Point a, Point b) {
Point result;
result.x = a.x + b.x;
result.y = a.y + b.y;
return result;
}
// 修改結(jié)構(gòu)體內(nèi)容
void scale_point(Point* p, int factor) {
p->x *= factor;
p->y *= factor;
}
編譯為動(dòng)態(tài)庫(kù):
gcc -shared -o struct_example.so -fPIC struct_example.c
Python調(diào)用代碼:
import ctypes
# 加載動(dòng)態(tài)庫(kù)
lib = ctypes.CDLL('./struct_example.so')
# 定義Point結(jié)構(gòu)體
class Point(ctypes.Structure):
_fields_ = [
("x", ctypes.c_int),
("y", ctypes.c_int)
]
# 設(shè)置函數(shù)參數(shù)和返回值類型
lib.add_points.argtypes = [Point, Point]
lib.add_points.restype = Point
lib.scale_point.argtypes = [ctypes.POINTER(Point), ctypes.c_int]
lib.scale_point.restype = None
# 調(diào)用add_points函數(shù)
p1 = Point(1, 2)
p2 = Point(3, 4)
result = lib.add_points(p1, p2)
print(f"({p1.x}, {p1.y}) + ({p2.x}, {p2.y}) = ({result.x}, {result.y})")
# 輸出: (1, 2) + (3, 4) = (4, 6)
# 調(diào)用scale_point函數(shù)
p = Point(5, 6)
lib.scale_point(ctypes.byref(p), 2)
print(f"縮放后的點(diǎn): ({p.x}, {p.y})")
# 輸出: 縮放后的點(diǎn): (10, 12)
3. 處理數(shù)組和指針
C代碼(保存為array_example.c):
#include <stdio.h>
// 計(jì)算數(shù)組元素之和
int sum_array(int* arr, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// 修改數(shù)組內(nèi)容
void multiply_array(int* arr, int size, int factor) {
for (int i = 0; i < size; i++) {
arr[i] *= factor;
}
}
編譯為動(dòng)態(tài)庫(kù):
gcc -shared -o array_example.so -fPIC array_example.c
Python調(diào)用代碼:
import ctypes
# 加載動(dòng)態(tài)庫(kù)
lib = ctypes.CDLL('./array_example.so')
# 創(chuàng)建C整數(shù)數(shù)組類型
IntArray5 = ctypes.c_int * 5 # 定義長(zhǎng)度為5的整數(shù)數(shù)組
# 設(shè)置函數(shù)參數(shù)類型
lib.sum_array.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int]
lib.sum_array.restype = ctypes.c_int
lib.multiply_array.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int]
lib.multiply_array.restype = None
# 調(diào)用sum_array函數(shù)
arr = IntArray5(1, 2, 3, 4, 5)
sum_result = lib.sum_array(arr, 5)
print(f"數(shù)組和: {sum_result}") # 輸出: 15
# 調(diào)用multiply_array函數(shù)
lib.multiply_array(arr, 5, 10)
print(f"修改后的數(shù)組: {[arr[i] for i in range(5)]}")
# 輸出: [10, 20, 30, 40, 50]
4. 調(diào)用C++類和函數(shù)(需要extern “C”)
C++代碼(保存為cpp_example.cpp):
#include <iostream>
using namespace std;
// C++類
class Calculator {
public:
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
};
// 封裝C++類的C接口
extern "C" {
// 創(chuàng)建對(duì)象
Calculator* Calculator_new() { return new Calculator(); }
// 釋放對(duì)象
void Calculator_delete(Calculator* calc) { delete calc; }
// 調(diào)用成員函數(shù)
int Calculator_add(Calculator* calc, int a, int b) { return calc->add(a, b); }
int Calculator_subtract(Calculator* calc, int a, int b) { return calc->subtract(a, b); }
}
編譯為動(dòng)態(tài)庫(kù):
g++ -shared -o cpp_example.so -fPIC cpp_example.cpp
Python調(diào)用代碼:
import ctypes
# 加載動(dòng)態(tài)庫(kù)
lib = ctypes.CDLL('./cpp_example.so')
# 定義函數(shù)參數(shù)和返回值類型
lib.Calculator_new.restype = ctypes.c_void_p
lib.Calculator_delete.argtypes = [ctypes.c_void_p]
lib.Calculator_add.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
lib.Calculator_add.restype = ctypes.c_int
lib.Calculator_subtract.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
lib.Calculator_subtract.restype = ctypes.c_int
# 創(chuàng)建Calculator對(duì)象
calc_ptr = lib.Calculator_new()
# 調(diào)用成員函數(shù)
result_add = lib.Calculator_add(calc_ptr, 10, 5)
result_sub = lib.Calculator_subtract(calc_ptr, 10, 5)
print(f"10 + 5 = {result_add}") # 輸出: 15
print(f"10 - 5 = {result_sub}") # 輸出: 5
# 釋放對(duì)象
lib.Calculator_delete(calc_ptr)
常見(jiàn)問(wèn)題與解決方案
找不到動(dòng)態(tài)庫(kù)文件
- 確保動(dòng)態(tài)庫(kù)文件在正確路徑下
- 使用絕對(duì)路徑加載庫(kù):
ctypes.CDLL('/path/to/library.so')
參數(shù)類型不匹配
- 始終顯式設(shè)置
argtypes和restype - 對(duì)于字符串,使用
ctypes.create_string_buffer()創(chuàng)建可變字節(jié)數(shù)組
- 始終顯式設(shè)置
處理C++類
- 必須使用
extern "C"封裝C++接口 - 通過(guò)指針管理對(duì)象生命周期(創(chuàng)建和銷毀)
- 必須使用
內(nèi)存管理問(wèn)題
- 手動(dòng)管理動(dòng)態(tài)分配的內(nèi)存(如使用
delete釋放C++對(duì)象) - 避免返回指向局部變量的指針
- 手動(dòng)管理動(dòng)態(tài)分配的內(nèi)存(如使用
通過(guò)ctypes調(diào)用C/C++動(dòng)態(tài)庫(kù)是Python與底層系統(tǒng)交互的強(qiáng)大方式,能夠在保持Python靈活性的同時(shí)獲得C/C++的高性能。
總結(jié)
到此這篇關(guān)于python調(diào)用C/C++動(dòng)態(tài)庫(kù)的文章就介紹到這了,更多相關(guān)python調(diào)用C/C++動(dòng)態(tài)庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
windows上安裝python3教程以及環(huán)境變量配置詳解
這篇文章主要介紹了windows上安裝python3教程以及環(huán)境變量配置詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
python人工智能算法之人工神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家介紹了python人工智能算法之人工神經(jīng)網(wǎng)絡(luò)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
安裝conda搭建python環(huán)境保姆級(jí)教程(超詳細(xì)!)
這篇文章主要給大家介紹了關(guān)于安裝conda搭建python環(huán)境保姆級(jí)教程的相關(guān)資料,conda可以理解為一個(gè)工具,也是一個(gè)可執(zhí)行命令,其核心功能是包管理和環(huán)境管理,需要的朋友可以參考下2023-11-11
Python深度學(xué)習(xí)之Unet?語(yǔ)義分割模型(Keras)
這篇文章主要介紹了語(yǔ)義分割任務(wù)中Unet一個(gè)有意思的模型-Keras。Keras是一個(gè)由Python編寫的開(kāi)源人工神經(jīng)網(wǎng)絡(luò)庫(kù),可進(jìn)行深度學(xué)習(xí)模型的設(shè)計(jì)、調(diào)試、評(píng)估、應(yīng)用和可視化。感興趣的小伙伴快來(lái)跟隨小編一起學(xué)習(xí)一下吧2021-12-12
python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5 UI主線程與耗時(shí)線程分離詳細(xì)方法實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5 UI主線程與耗時(shí)線程分離詳細(xì)方法實(shí)例,需要的朋友可以參考下2020-02-02

