1. 程式人生 > 其它 >dll檔案使用python和c++呼叫

dll檔案使用python和c++呼叫

技術標籤:Python

dll是Windows上的動態庫檔案,常常將需要使用的函式封裝在dll檔案中,因此dll檔案是不存在main入口的,把它想成函式就行,其內容並不神祕。

只是使用的時候需要對dll檔案進行載入,載入dll檔案後就可以使用裡面封裝好的函數了。

c++裡面呼叫很簡單,Windows封裝好了,只需要#include<Windows.h>就可以直接使用,而要想使用Python呼叫需要使用ctypes庫。

這個測試的dll檔案是隻定義了一個函式add,定義了一個加法運算:

可以看到有一個add函式被暴露出來了

下面使用Python測試一下效果:

from ctypes import cdll

_dll = cdll.LoadLibrary("./dllTest.dll")
res = _dll.add(3,2)
print(res)

執行效果:

c++呼叫:

#include <iostream>
#include<Windows.h>

int main()
{
   HMODULE module= LoadLibrary(L"dllTest.dll");
   if (module == NULL)
   {
	   return 0;
   }
   
   typedef int(*AddFunc)(int, int);
   AddFunc add;  
   add = (AddFunc)GetProcAddress(module, "add");
   int re = add(2,5);
   std::cout << re <<std::endl;

	return 0;
}

執行結果: