C++中的函数指针和未知数量的参数

Emi*_*l D 7 c++ dll function-pointers loadlibrary

我遇到了以下奇怪的代码块.想象你有以下typedef:

typedef int (*MyFunctionPointer)(int param_1, int param_2);
Run Code Online (Sandbox Code Playgroud)

然后,在函数中,我们尝试以下列方式从DLL运行函数:

LPCWSTR DllFileName;    //Path to the dll stored here
LPCSTR _FunctionName;   // (mangled) name of the function I want to test

MyFunctionPointer functionPointer;

HINSTANCE hInstLibrary = LoadLibrary( DllFileName );
FARPROC functionAddress = GetProcAddress( hInstLibrary, _FunctionName );

functionPointer = (MyFunctionPointer) functionAddress;

//The values are arbitrary
int a = 5;
int b = 10;
int result = 0;

result = functionPointer( a, b );  //Possible error?
Run Code Online (Sandbox Code Playgroud)

问题是,没有任何方法可以知道我们使用LoadLibrary获取的地址的功能是否有两个整数参数.dll名称由用户在运行时提供,然后列出导出函数的名称和用户选择要测试的那个(再次,在运行时:S:S).那么,通过在最后一行执行函数调用,我们不是打开可能的堆栈损坏的大门吗?我知道这会编译,但是在我们将错误的参数传递给我们指向的函数的情况下会发生什么样的运行时错误?

Rap*_*rre 4

如果预期和使用的参数数量或类型以及调用约定不同,我可以想到三个错误:

  • 如果调用约定不同,会读取到错误的参数值
  • 如果函数实际上期望的参数多于给定的参数,则将使用随机值作为参数(我会让你想象一下如果涉及指针的后果)
  • 在任何情况下,返回地址都将是完全垃圾,因此函数返回后将立即运行具有随机数据的随机代码。

简而言之:Undefined behavior