亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從DLL動態加載函數

從DLL動態加載函數

C++
慕森王 2019-08-30 17:43:54
我正在查看.dll文件,我了解它們的用法,我正在嘗試了解如何使用它們。我創建了一個.dll文件,其中包含一個返回名為funci()的整數的函數使用此代碼,我(想)我已將.dll文件導入項目(沒有投訴):#include <windows.h>#include <iostream>int main() {  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop  \\fgfdg\\dgdg\\test.dll");  if (hGetProcIDDLL == NULL) {    std::cout << "cannot locate the .dll file" << std::endl;  } else {    std::cout << "it has been called" << std::endl;    return -1;  }  int a = funci();  return a;}# funci function int funci() {  return 40;}但是,當我嘗試編譯我認為已導入.dll的.cpp文件時,我遇到以下錯誤:C:\Documents and Settings\User\Desktop\fgfdg\onemore.cpp||In function 'int main()':|C:\Documents and Settings\User\Desktop\fgfdg\onemore.cpp|16|error: 'funci' was not     declared in this scope|||=== Build finished: 1 errors, 0 warnings ===|我知道.dll與頭文件有所不同,所以我知道我可以;導入這樣的函數,但這是我能想到的最好的表明我已經嘗試過的。我的問題是,如何使用“hGetProcIDDLL”指針訪問.dll中的函數。我希望這個問題有道理,我再也不會咆哮一些錯誤的樹了。
查看完整描述

2 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

LoadLibrary不會做你認為它做的事情。它加載DLL到當前進程的內存,但它并不會神奇地導入它定義的功能!這是不可能的,因為LoadLibrary在運行時調用時,鏈接器會在編譯時解析函數調用(請記住,C ++是一種靜態類型語言)。


您需要一個單獨的WinAPI函數來獲取動態加載函數的地址:GetProcAddress。



#include <windows.h>

#include <iostream>


/* Define a function pointer for our imported

 * function.

 * This reads as "introduce the new type f_funci as the type: 

 *                pointer to a function returning an int and 

 *                taking no arguments.

 *

 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)

 * with the exported function. __stdcall is the convention used by the WinAPI

 */

typedef int (__stdcall *f_funci)();


int main()

{

  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");


  if (!hGetProcIDDLL) {

    std::cout << "could not load the dynamic library" << std::endl;

    return EXIT_FAILURE;

  }


  // resolve function address here

  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");

  if (!funci) {

    std::cout << "could not locate the function" << std::endl;

    return EXIT_FAILURE;

  }


  std::cout << "funci() returned " << funci() << std::endl;


  return EXIT_SUCCESS;

}

此外,您應該正確地從DLL 導出您的函數。這可以這樣做:


int __declspec(dllexport) __stdcall funci() {

   // ...

}

正如Lundin指出的那樣,如果您不再需要它,那么將句柄釋放到庫中是一種很好的做法。如果沒有其他進程仍然擁有同一DLL的句柄,這將導致它被卸載。


查看完整回答
反對 回復 2019-08-30
  • 2 回答
  • 0 關注
  • 737 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號