【问题标题】:interfacing with a DLL function through GetProcAddress() in C++ and visual studio通过 C++ 和 Visual Studio 中的 GetProcAddress() 与 DLL 函数交互
【发布时间】:2014-05-31 01:50:56
【问题描述】:

好的,伙计们,这是我上一篇文章的一个扩展,它已经解决,这部分工作得很好(下面的链接)

Not finding function using GetProcAddress() C++ VBexpress 13

不幸的是,另一个误解出现了。下面是我要参考的代码:

#include "stdafx.h"
#include <iostream>
#include "Windows.h"
#include <stdio.h> 

typedef int(__cdecl *MYPROC)(LPWSTR);

using namespace std;

int main()
{

HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

hinstLib = LoadLibrary(TEXT("testDLL.dll"));
if (hinstLib != NULL)
{
    ProcAdd = (MYPROC)GetProcAddress(hinstLib, "?Add@MyMathFuncs@MathFuncs@@SANNN@Z");

    // If the function address is valid, call the function.

    if (NULL != ProcAdd)
    {
        fRunTimeLinkSuccess = TRUE;
        c=(ProcAdd)(L"something here");
    }
    fFreeResult = FreeLibrary(hinstLib);
}

return 0;

}

问题:与函数交互时遇到问题。程序识别 DLL 和函数。我确信它与 typedef、对 ProcAdd 的分配以及我对函数的实际调用有关。在这个例子中,我正在调用一个将双打加在一起的函数。显然我需要通过 2 双打。似乎逻辑决定我可以用'typedef int(__cdecl *MYPROC)(double,double);'替换typedef或类似的东西,用 2 个双精度替换 L"something here" 并将其分配给一个值。当我这样做时没有运行时错误,但我只是为返回的数字提供了一个很大的负数。这两条线到底发生了什么?不幸的是,我什至不确定具体要做什么。我明白 _cdecl 是什么。

简短背景:我必须与一个我没有 .lib 文件的 DLL 接口。我遇到了麻烦,所以我用http://msdn.microsoft.com/en-us/library/ms235636.aspx 的 MS 教程制作了一个 DLL,并用上面的代码引用了那个 DLL,如果我没记错的话,它取自另一个 MS 教程。

对于理解这些基本概念的任何帮助将不胜感激。谢谢!

【问题讨论】:

  • Obviously i need to pass 2 doubles. it seems like logic would dictate i could replace the typedef with 'typedef int(__cdecl *MYPROC)(double,double);' or something similar and replace the L"something here" with 2 doubles and assign it to a value。看起来确实如此。为什么不这样做? What exactly are happening in these 2 lines that are throwing me? 未定义的行为正在发生。

标签: c++ dll


【解决方案1】:

typedef int(__cdecl *MYPROC)(LPWSTR); 正在为函数指针引入类型定义,用它翻译的话来说:

“MYPROC 是一个指向函数的指针,该函数接受一个 LPWSTR 并返回一个 int”。所以你的假设是正确的。你的逻辑也是正确的,因为你想做一些事情:

typedef double(__cdecl *MYPROC)(double, double);
   ....
MYPROC pMyFun = (MYPROC)GetProcAddress(hinstLib, "?Add@MyMathFuncs@MathFuncs@@SANNN@Z");
   ....
pMyFun(1.0,2.0);

这样做的目的是在第一行引入一种新类型。然后我们声明一个这种类型的变量,然后分配给它感兴趣的函数的地址,最后,我们使用这个指针调用这个函数。如果您不熟悉函数指针this tutorial may help

鉴于此,我有两个问题:

(1) 你从哪里得到函数的名称? (2) TestDll.dll 是你写的dll,还是你需要接口的那个?

【讨论】:

  • MSDN 文章中的 Microsoft 示例代码描述了如何创建 DLL。
  • 好吧,很高兴听到我离得不远。函数名来自于使用 Visual Studio 提供的 dumpbin 实用程序来获取 DLL 中损坏的函数名。
  • 你如何为从 DLL 返回的类做这件事?
  • @darkgaze 查看这篇 MSDN 文章 msdn.microsoft.com/en-us/library/81h27t8c.aspx,它描述了如何使用库中的类。
猜你喜欢
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
相关资源
最近更新 更多