(如何)dll 可以调用在其加载程序中实现的函数?

(How) can a dll call a function that is implemented in its loading program?

通常我们在windows上加载一个dll并调用它的函数,标记为__declspec(dllexport),但是我可以从一个dll调用一个在加载程序中实现的函数吗?

首先说这可以在 Linux 上完成,请查看我之前询问的

我写了一个测试程序来测试这个: CMakeList.txt(抱歉,我是 Windows 编程新手,不知道如何使用 visual studio):

cmake_minimum_required(VERSION 3.16)
project(untitled4)

set(CMAKE_CXX_STANDARD 17)

add_library(lib1 SHARED lib1.cpp)

add_executable(untitled4 main.cpp)

main.cpp

#include "iostream"
#include "windows.h"
extern "C" {
  // this is the function I want to get called from dll
__declspec(dllexport)
float get_e() {
  return 2.71;
}
}
int main() {
  auto *handler = LoadLibrary("lib1.dll");
  if (!handler) {
    std::cerr << ERROR_DELAY_LOAD_FAILED << std::endl;
    exit(1);
  }
  auto p = (float (*)()) GetProcAddress(handler, "get_pi");
  std::cout << p() << std::endl;
}

lib1.cpp:

#include "iostream"
extern "C" {
  // implemented in main.cpp
__declspec(dllimport)
float get_e();

__declspec(dllexport)
float get_pi() {
  std::cout << get_e() << std::endl; // comment this line will compile, just like the normal case
  return 3.14;
}
}

构建lib1时编译会失败:

NMAKE : fatal error U1077: '"C:\Program Files\JetBrains\CLion 2020.1.1\bin\cmake\win\bin\cmake.exe"' : return code '0xffffffff'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio19\BuildTools\VC\Tools\MSVC.27.29110\bin\HostX86\x64\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio19\BuildTools\VC\Tools\MSVC.27.29110\bin\HostX86\x64\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio19\BuildTools\VC\Tools\MSVC.27.29110\bin\HostX86\x64\nmake.exe"' : return code '0x2'
LINK Pass 1: command "C:\PROGRA~2\MICROS~219\BUILDT~1\VC\Tools\MSVC27~1.291\bin\Hostx86\x64\link.exe /nologo @CMakeFiles\lib1.dir\objects1.rsp /out:lib1.dll /implib:lib1.lib /pdb:C:\Users\derwe\CLionProjects\untitled\cmake-build-debug\lib1.pdb /dll /version:0.0 /machine:x64 /debug /INCREMENTAL kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\lib1.dir/intermediate.manifest CMakeFiles\lib1.dir/manifest.res" failed (exit code 1120) with the following output:
   Creating library lib1.lib and object lib1.exp
lib1.cpp.obj : error LNK2019: unresolved external symbol __imp_get_e referenced in function get_pi
lib1.dll : fatal error LNK1120: 1 unresolved externals
Stop.

那么我可以在 windows 上这样做吗?那就是从一个dll中调用main中的一个函数?

P.S。感谢在 dll 中添加注册表函数并通过它传递 get_e 的想法,但在我的实际情况下不能考虑。

由于您对 .dll 使用后期绑定,因此您可以对可执行文件中定义的函数执行相同的操作。只需使用此进程句柄以相同的方式调用 GetProcAddress(因为它已经在地址 space 中)。这是一些(伪)代码:

auto proc = GetModuleHandle(nullptr);
auto get_e = reinterpret_cast<float (*) ()>(GetProcAddress(proc, "get_e"));