簡體   English   中英

為什么GetProcAddress不起作用?

[英]Why GetProcAddress doesn't work?

首先,我創建一個名為SimpleDll.dll的簡單dll,它的頭文件:

// SimpleDll.h
#ifdef MYLIBAPI
#else
#define MYLIBAPI __declspec(dllimport)
#endif

MYLIBAPI int Add(int a. int b);

其源代碼:

// SimpleDll.c
#include <windows.h>

#define MYLIBAPI __declspec(dllexport)
#include "SimpleDll.h"    

int Add(int a, int b)
{
    return a + b;
}

然后我在另一個項目中調用它,它工作正常:

// TestSimpleDll.c
#include "stdafx.h"
#include <windows.h>
#include "SimpleDll.h"

#pragma comment(lib, "SimpleDll.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    printf("%d", Add(10, 30));    // Give the expected result 40
    return 0;
}

但是,當我調用GetProcAddress獲取它的地址時,它不起作用!

// TestSimpleDll2.c
#include "stdafx.h"
#include <windows.h>
#include "SimpleDll.h"

#pragma comment(lib, "SimpleDll.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    printf("%d", Add(10, 30));    // Give the expected result 40
    HMODULE hModule = GetModuleHandleA("SimpleDll.dll");    // hModule is found
    PROC add_proc       = GetProcAddress(hModule, "Add");     // but Add is not found !
    //  add_proc is NULL!
    return 0;
}

謝謝你的幫助。 (PS:我在Windows7上使用VS2010)
更新:
這是依賴walker為SimpleDll.dll文件顯示的SimpleDll.dll

在此輸入圖像描述

如果要導出GetProcAddress的名稱,則應使用.def文件。 否則你將不得不處理c ++名稱修改和符號裝飾。

您可以通過將函數聲明為extern "C"來避免修改,但避免裝飾的唯一方法是使用.DEF文件。

還有一件事 - 在Dependency walker中 - 使用F10在裝飾和未裝飾的名稱之間切換。

Dependency Walker是解決這類DLL問題的絕佳工具。

我假設您正在將DLL編譯為C代碼。 否則,C ++執行會導致問題的名稱修改。

要避免名稱修改,只需將導出定義包裝在extern“C”中。

extern "C" {
    MYLIBAPI int Add(int a. int b);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM