亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python調(diào)用C/C++動(dòng)態(tài)庫(kù)的實(shí)踐案例

 更新時(shí)間:2025年09月30日 09:37:59   作者:越甲八千  
python是動(dòng)態(tài)語(yǔ)言,c++是靜態(tài)語(yǔ)言,下面這篇文章主要介紹了python調(diào)用C/C++動(dòng)態(tài)庫(kù)的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

Python通過(guò)ctypes模塊可以方便地調(diào)用C/C++編寫的動(dòng)態(tài)庫(kù)(Windows下為DLL,Linux下為SO文件)。這種方式允許Python與底層系統(tǒng)進(jìn)行高效交互,廣泛用于硬件控制、高性能計(jì)算等場(chǎng)景。

基本原理

  1. 動(dòng)態(tài)庫(kù)加載:使用ctypes.CDLL(加載C庫(kù))或ctypes.WinDLL(加載Windows特定的stdcall調(diào)用約定的DLL)加載動(dòng)態(tài)庫(kù)文件
  2. 函數(shù)參數(shù)與返回值類型聲明:明確指定C函數(shù)的參數(shù)類型和返回值類型,確保數(shù)據(jù)傳遞正確
  3. 數(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)題與解決方案

  1. 找不到動(dòng)態(tài)庫(kù)文件

    • 確保動(dòng)態(tài)庫(kù)文件在正確路徑下
    • 使用絕對(duì)路徑加載庫(kù):ctypes.CDLL('/path/to/library.so')
  2. 參數(shù)類型不匹配

    • 始終顯式設(shè)置argtypesrestype
    • 對(duì)于字符串,使用ctypes.create_string_buffer()創(chuàng)建可變字節(jié)數(shù)組
  3. 處理C++類

    • 必須使用extern "C"封裝C++接口
    • 通過(guò)指針管理對(duì)象生命周期(創(chuàng)建和銷毀)
  4. 內(nèi)存管理問(wèn)題

    • 手動(dòng)管理動(dòng)態(tài)分配的內(nèi)存(如使用delete釋放C++對(duì)象)
    • 避免返回指向局部變量的指針

通過(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)文章

  • Python os.access()用法實(shí)例

    Python os.access()用法實(shí)例

    在本篇文章里小編給大家分享了關(guān)于Python os.access()用法實(shí)例內(nèi)容以及相關(guān)知識(shí)點(diǎn),需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • 詳解如何使用Python和正則表達(dá)式處理XML表單數(shù)據(jù)

    詳解如何使用Python和正則表達(dá)式處理XML表單數(shù)據(jù)

    在日常的Web開(kāi)發(fā)中,處理表單數(shù)據(jù)是一個(gè)常見(jiàn)的任務(wù),而XML是一種常用的數(shù)據(jù)格式,用于在不同的系統(tǒng)之間傳遞和存儲(chǔ)數(shù)據(jù),本文通過(guò)闡述一個(gè)技術(shù)問(wèn)題并給出解答的方式,介紹如何使用Python和正則表達(dá)式處理XML表單數(shù)據(jù),需要的朋友可以參考下
    2023-09-09
  • docker-py 用Python調(diào)用Docker接口的方法

    docker-py 用Python調(diào)用Docker接口的方法

    今天小編就為大家分享一篇docker-py 用Python調(diào)用Docker接口的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-08-08
  • Python中使用正則表達(dá)式替換特定格式的文本

    Python中使用正則表達(dá)式替換特定格式的文本

    在Python中使用正則表達(dá)式替換特定格式的文本,主要通過(guò)re模塊的sub()和subn()函數(shù)實(shí)現(xiàn),本文給大家介紹Python中使用正則表達(dá)式替換特定格式的文本,感興趣的朋友一起看看吧
    2025-09-09
  • Python中的aa-whisper包語(yǔ)法、參數(shù)和實(shí)際應(yīng)用案例小結(jié)

    Python中的aa-whisper包語(yǔ)法、參數(shù)和實(shí)際應(yīng)用案例小結(jié)

    aa-whisper是基于Whisper的增強(qiáng)工具包,支持99種語(yǔ)言、實(shí)時(shí)語(yǔ)音處理、批量轉(zhuǎn)換及多種輸出格式,本文給大家介紹Python中的aa-whisper包語(yǔ)法、參數(shù)和實(shí)際應(yīng)用案例小結(jié),感興趣的朋友一起看看吧
    2025-09-09
  • Python實(shí)現(xiàn)的簡(jiǎn)單文件傳輸服務(wù)器和客戶端

    Python實(shí)現(xiàn)的簡(jiǎn)單文件傳輸服務(wù)器和客戶端

    這篇文章主要介紹了Python實(shí)現(xiàn)的簡(jiǎn)單文件傳輸服務(wù)器和客戶端,本文直接給出Server和Client端的實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2015-04-04
  • Python?jpg快速轉(zhuǎn)png并調(diào)整大小方式

    Python?jpg快速轉(zhuǎn)png并調(diào)整大小方式

    這篇文章主要介紹了Python實(shí)現(xiàn)jpg快速轉(zhuǎn)png并調(diào)整大小方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Python中uuid模塊生成唯一標(biāo)識(shí)符的方法詳解

    Python中uuid模塊生成唯一標(biāo)識(shí)符的方法詳解

    這篇文章主要給大家介紹了關(guān)于Python中uuid模塊生成唯一標(biāo)識(shí)符的相關(guān)資料,uuid庫(kù)是Python標(biāo)準(zhǔn)庫(kù)中的一個(gè)功能強(qiáng)大的庫(kù),可以用于生成全局唯一標(biāo)識(shí)符(UUID),文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-08-08
  • Python畫圖常用命令大全(詳解)

    Python畫圖常用命令大全(詳解)

    這篇文章主要介紹了Python畫圖常用命令大全,內(nèi)容包括,matplotlib庫(kù)默認(rèn)英文字體,讀取exal方法,論文圖片的類型和格式,柱狀圖擴(kuò)展等知識(shí),需要的朋友可以參考下
    2021-09-09
  • python內(nèi)存管理機(jī)制原理詳解

    python內(nèi)存管理機(jī)制原理詳解

    這篇文章主要介紹了python內(nèi)存管理機(jī)制原理詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08

最新評(píng)論