編程學習筆記 2023-08-25 #00001 主題 : C++ Dll編譯及Python調用基礎


編程學習筆記 2023-08-25 #00001     

主題 : C++ Dll編譯及Python調用基礎


由C++ 編譯至.dll,並以Python<ctypes>調用嘗試。

        平台 : 22H2 Window 10

        編譯器 : g++ 13.1.0 , Python 3.11.1

        IDE : Visual Studio Code 1.80.0

 

    測試內容為「把"Hello World ! "的C++ Function於Python 進行調用」。

i. dll編譯

最初的C++Script如下 : 

#include <iostream>

using namespace std;
//使用std命名空間


//定義名為TESTFunc的Function extern "C" int TESTFunc(){ std::cout << "Hello World!";
    //Output 字串"Hello World" return 0; }

就上述的程式碼使用g++進行編譯,

g++ -Wall -Wextra -O -ansi -pedantic -fPIC -shared Main.cpp -o TEST.dll

於Python調用時(調用部分後文會再提及)結果為Error,初步推測為Dependency問題

FileNotFoundError: Could not find module 'd:\_TESTing\C++DLL\TEST.dll' (or one of its dependencies). Try using the full path with constructor syntax.

嘗試於g++編譯指令中加上 -static Option

g++ -static -Wall -Wextra -O -ansi -pedantic -fPIC -shared Main.cpp -o TEST.dll

終於成功調用,並Output了"Hello World!"

[Running] python -u "d:\_TESTing\C++DLL\Main.py"
Hello World!
[Done] exited with code=0 in 0.154 seconds


ii. Python 調用

Python 對Dll的調用十分簡單,只要使用Python 的ctypes模組便可以。
由於是Standard庫中的內容,因此不需要特別用pip安裝。

from ctypes import cdll
#import ctypes 中的 cdll
dll = cdll.LoadLibrary("./TEST.dll")

#讀取TEST.dll dll.TESTFunc()
#調用TESTFunc
[Running] python -u "d:\_TESTing\C++DLL\Main.py"
Hello World!
[Done] exited with code=0 in 0.154 seconds


結論

雖然VS Code在設置了Code Runner後只需要按下Run Code便會自動進行編譯及運行,
但顯然在程式語言的學習中,靈活使用編譯器亦是重要的一環。
初學期大多只會學習/練習程式語言中的Syntax,
但編譯器的Command、Option都要多方嘗試,
畢竟,源代碼作為一個程式的一部分,並無法自己完成任務,而要由多個檔案合作,
而要整合不同的.cpp的Relationship就要用到g++不同的Option。

如 : 
g++ -static : 靜態程式庫,加入後編譯執行檔無需Dependency,但執行檔會較大。
g++ -share : 用於創建分享程式庫


熱門文章