最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中調用C++代碼的方法總結

 更新時間:2025年11月18日 08:34:49   作者:夢_魚  
這篇文章主要為大家詳細介紹了Python中調用C++代碼的相關方法,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考一下

1. extern "C" {} 包裹導出函數(shù)

// C++ 中存在名稱修飾,通過 extern "C" {} 將C++函數(shù)導出為C函數(shù)
// 1. 為類的每個函數(shù)創(chuàng)建C風格接口,第一個參數(shù)為對象指針
// 2. 提供 create(構造) destroy(析構) 函數(shù)管理對象的生命周期
#include <string>

// C++類定義
class Calculator {
private:
int base;
public:
Calculator(int b) : base(b) {}
int add(int a) { return base + a; }
std::string greet(const std::string& name) { return "Hello, " + name; }
};

// C風格函數(shù)
extern "C" {

// 創(chuàng)建對象(對應構造函數(shù))
Calculator* Calculator_create(int base) {
return new Calculator(base);
}

// 銷毀對象(對應析構函數(shù))
void Calculator_destroy(Calculator* obj) {
delete obj;
}

// 封裝成員函數(shù)
int Calculator_add(Calculator* obj, int a) {
return obj->add(a);
}

// 字符串處理需要特殊轉換(C++ string -> char*)
const char* Calculator_greet(Calculator* obj, const char* name) {
static std::string result;  // 注意:靜態(tài)變量在多線程中不安全
result = obj->greet(std::string(name));
return result.c_str();
}

}

2. 將C++代碼編譯為動態(tài)庫

# 使用C++編譯器,保留 -f PIC -shared 參數(shù)生成位置無關的動態(tài)庫
g++ -shared -fPIC -o libcalc.so example.cpp

3.python ctypes調用動態(tài)庫

使用python的ctypes庫調用動態(tài)庫(加載動態(tài)庫 -> 定義C函數(shù)的輸入?yún)?shù)與返回參數(shù) -> 調用動態(tài)庫函數(shù))

  • 用 c_void_p 類型存儲C++對象的指針
  • 字符串通過bytes類型轉換(encode/decode)
  • 實現(xiàn) del 方法自動釋放C++對象,避免內存泄漏
import ctypes
import os


class CalculatorWrapper:
    """C++ Calculator類的Python封裝器"""

    def __init__(self):
        # 加載動態(tài)庫
        self.lib = self._load_library()
        # 配置C接口函數(shù)原型
        self._setup_functions()
        # 存儲C++對象指針
        self.obj_ptr = None

    def _load_library(self):
        """根據(jù)操作系統(tǒng)加載對應的庫文件"""
        try:
            if os.name == "nt":
                return ctypes.CDLL("./calc.dll")
            elif os.name == "posix":
                return ctypes.CDLL("./libcalc.so")
            else:
                raise OSError("不支持的操作系統(tǒng)")
        except OSError as e:
            raise RuntimeError(f"加載庫失敗: {e}")

    def _setup_functions(self):
        """定義C接口函數(shù)的參數(shù)類型和返回值類型"""
        # 創(chuàng)建對象
        self.lib.Calculator_create.argtypes = [ctypes.c_int]
        self.lib.Calculator_create.restype = ctypes.c_void_p  # 返回對象指針

        # 銷毀對象
        self.lib.Calculator_destroy.argtypes = [ctypes.c_void_p]
        self.lib.Calculator_destroy.restype = None

        # 加法函數(shù)
        self.lib.Calculator_add.argtypes = [ctypes.c_void_p, ctypes.c_int]
        self.lib.Calculator_add.restype = ctypes.c_int

        # 字符串問候函數(shù)
        self.lib.Calculator_greet.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
        self.lib.Calculator_greet.restype = ctypes.c_char_p

    def create(self, base_value):
        """創(chuàng)建C++ Calculator實例"""
        self.obj_ptr = self.lib.Calculator_create(base_value)
        if not self.obj_ptr:
            raise RuntimeError("創(chuàng)建C++對象失敗")

    def add(self, a):
        """調用加法方法"""
        self._check_object()
        return self.lib.Calculator_add(self.obj_ptr, a)

    def greet(self, name):
        """調用問候方法(處理字符串轉換)"""
        self._check_object()
        # Python字符串轉C字符串(bytes類型)
        c_name = name.encode('utf-8')
        result_ptr = self.lib.Calculator_greet(self.obj_ptr, c_name)
        # C字符串轉Python字符串
        return result_ptr.decode('utf-8')

    def _check_object(self):
        """檢查對象是否已創(chuàng)建"""
        if not self.obj_ptr:
            raise RuntimeError("請先調用create()創(chuàng)建對象")

    def __del__(self):
        """對象銷毀時自動釋放C++資源"""
        if self.obj_ptr:
            self.lib.Calculator_destroy(self.obj_ptr)


if __name__ == "__main__":
    try:
        calc = CalculatorWrapper()
        calc.create(100)  # 初始化base值為100

        print(f"100 + 50 = {calc.add(50)}")  # 輸出150
        print(calc.greet("C++"))  # 輸出"Hello, Python"
    except Exception as e:
        print(f"錯誤: {e}")

4.方法補充

以下是小編整理的Python調用C++代碼的其他方法,大家可以參考一下

使用ctypes調用C/C++代碼

編寫C/C++代碼

首先,我們編寫一個簡單的C++函數(shù),并將其編譯為共享庫(.so文件)。

// mylib.cpp
#include <iostream>
extern "C" {
    int add(int a, int b) {
        std::cout << "add called" << std::endl;
        return a + b;
    }
}

編譯C/C++代碼

使用以下命令將C++代碼編譯為共享庫:

g++ -shared -o libmylib.so -fPIC mylib.cpp
  • -shared:生成共享庫。
  • -o libmylib.so:指定輸出文件名為libmylib.so。
  • -fPIC:生成位置無關代碼(Position Independent Code),這是共享庫所必需的。

在Python中調用C/C++函數(shù)

使用ctypes庫加載共享庫并調用C++函數(shù):

import ctypes
import os

# 加載共享庫
lib = ctypes.CDLL(os.path.abspath("libmylib.so"))

# 調用 C++ 函數(shù)
result = lib.add(3, 4)  # add called
print(f"Result: {result}")  # 輸出: Result: 7

使用pybind11調用C/C++代碼

需要 pip install pybind11

pybind11 的名字中的 11 表示它需要 C++11 或更高版本 的支持

編寫C/C++代碼

pybind11是一個輕量級的C++庫,用于將C++代碼暴露給Python。我們編寫一個簡單的C++函數(shù),并使用pybind11將其綁定到Python。

// mylib_pybind.cpp
#include <pybind11/pybind11.h>
#include <iostream>

int add(int a, int b) {
    std::cout << "add called from pybind" << std::endl;
    return a + b;
}

PYBIND11_MODULE(mylib_pybind, m) {
    m.def("add", &add, "A function that adds two numbers");
}

編譯C/C++代碼

使用以下命令將C++代碼編譯為Python模塊:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) mylib_pybind.cpp -o mylib_pybind$(python3-config --extension-suffix)

生成了 mylib_pybind.cpython-311-x86_64-linux-gnu.so 文件

  • -O3:優(yōu)化級別為3,生成高度優(yōu)化的代碼。
  • -Wall:啟用所有警告。
  • -shared:生成共享庫。
  • -std=c++11:使用C++11標準。
  • -fPIC:生成位置無關代碼。
  • $(python3 -m pybind11 --includes):獲取pybind11的頭文件路徑。
  • -o mylib_pybind$(python3-config --extension-suffix):指定輸出文件名,并使用Python的擴展名后綴。

在Python中調用C/C++函數(shù)

import mylib_pybind as mylib

result = mylib.add(3, 4)  # add called from pybind
print(f"Result: {result}")  # 輸出: Result: 7

c++調用python代碼

# example.py
def add(a, b):
    return a + b
#include <pybind11/embed.h>  // 嵌入 Python 解釋器
#include <iostream>

namespace py = pybind11;

int main() {
    // 啟動 Python 解釋器
    py::scoped_interpreter guard{};

    // 導入 Python 模塊
    py::module_ example = py::module_::import("example");

    // 調用 Python 函數(shù)
    py::object result = example.attr("add")(3, 4);
    std::cout << "Result: " << result.cast<int>() << std::endl;  // 輸出: Result: 7

    return 0;
}
g++ -o call_py call_py.cpp -I/opt/conda/envs/ai/include/python3.10/ $(python3 -m pybind11 --includes) -L/opt/conda/envs/ai/lib -lpython3.10

echo 'export LD_LIBRARY_PATH=/opt/conda/envs/ai/lib:$LD_LIBRARY_PATH' >> ~/.bashrc
source ~/.bashrc

執(zhí)行 ./call_py

到此這篇關于Python中調用C++代碼的方法總結的文章就介紹到這了,更多相關Python調用C++代碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python中urllib模塊用法實例詳解

    python中urllib模塊用法實例詳解

    這篇文章主要介紹了python中urllib模塊用法,以實例形式詳細分析了python中urllib模塊代替PHP的curl操作方法,具有不錯的借鑒價值,需要的朋友可以參考下
    2014-11-11
  • OpenCV半小時掌握基本操作之腐蝕膨脹

    OpenCV半小時掌握基本操作之腐蝕膨脹

    這篇文章主要介紹了OpenCV基本操作之腐蝕膨脹,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • Blender?Python編程實現(xiàn)批量導入網(wǎng)格并保存渲染圖像

    Blender?Python編程實現(xiàn)批量導入網(wǎng)格并保存渲染圖像

    這篇文章主要為大家介紹了Blender?Python?編程實現(xiàn)批量導入網(wǎng)格并保存渲染圖像示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • python銀行系統(tǒng)實現(xiàn)源碼

    python銀行系統(tǒng)實現(xiàn)源碼

    這篇文章主要為大家詳細介紹了python銀行系統(tǒng)實現(xiàn)源碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-10-10
  • Python實現(xiàn)刪除Android工程中的冗余字符串

    Python實現(xiàn)刪除Android工程中的冗余字符串

    這篇文章主要介紹了Python實現(xiàn)刪除Android工程中的冗余字符串,本文實現(xiàn)的是刪除Android資源(語言)國際化機制中的一些冗余字符串,需要的朋友可以參考下
    2015-01-01
  • Pycharm常用快捷鍵總結及配置方法

    Pycharm常用快捷鍵總結及配置方法

    這篇文章主要介紹了Pycharm常用快捷鍵總結及配置方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-11-11
  • python 簡單的股票基金爬蟲

    python 簡單的股票基金爬蟲

    最近基金非?;鸨?,很多原本不投資、不理財人,也開始討論、參與買基金了。根據(jù)投資對象的不同,基金分為股票型基金、債券基金、混合型基金、貨幣基金。所以今天我們就來看看,這些基金公司都喜歡買那些公司的股票。
    2021-06-06
  • Python 稀疏矩陣-sparse 存儲和轉換

    Python 稀疏矩陣-sparse 存儲和轉換

    這篇文章主要介紹了Python 稀疏矩陣-sparse 存儲和轉換的相關資料,需要的朋友可以參考下
    2017-05-05
  • Python3.5內置模塊之shelve模塊、xml模塊、configparser模塊、hashlib、hmac模塊用法分析

    Python3.5內置模塊之shelve模塊、xml模塊、configparser模塊、hashlib、hmac模塊用法

    這篇文章主要介紹了Python3.5內置模塊之shelve模塊、xml模塊、configparser模塊、hashlib、hmac模塊,結合實例形式較為詳細的分析了shelve、xml、configparser、hashlib、hmac等模塊的功能及使用方法,需要的朋友可以參考下
    2019-04-04
  • Python強化練習之PyTorch opp算法實現(xiàn)月球登陸器

    Python強化練習之PyTorch opp算法實現(xiàn)月球登陸器

    在面向對象出現(xiàn)之前,我們采用的開發(fā)方法都是面向過程的編程(OPP)。面向過程的編程中最常用的一個分析方法是“功能分解”。我們會把用戶需求先分解成模塊,然后把模塊分解成大的功能,再把大的功能分解成小的功能,整個需求就是按照這樣的方式,最終分解成一個一個的函數(shù)
    2021-10-10

最新評論

鄂尔多斯市| 阿城市| 靖宇县| 东源县| 和静县| 金沙县| 麦盖提县| 太白县| 简阳市| 西丰县| 兰坪| 杨浦区| 全州县| 永安市| 九龙坡区| 碌曲县| 菏泽市| 西吉县| 从化市| 南溪县| 尉犁县| 上林县| 疏附县| 乌兰县| 嘉祥县| 荣昌县| 霍山县| 阿拉善右旗| 满洲里市| 湖口县| 侯马市| 宁南县| 兴国县| 巴彦淖尔市| 郧西县| 时尚| 霍州市| 鹿邑县| 广河县| 新津县| 定结县|