【发布时间】:2021-03-13 14:24:00
【问题描述】:
通常我们在windows上加载一个dll并调用它的函数,标记为__declspec(dllexport),但是我可以从dll调用一个在加载的程序中实现的函数吗?
首先说这可以在 Linux 上完成,查看我之前问过的question。
我写了一个测试程序来测试这个: 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 Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\bin\HostX86\x64\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\bin\HostX86\x64\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\bin\HostX86\x64\nmake.exe"' : return code '0x2'
LINK Pass 1: command "C:\PROGRA~2\MICROS~2\2019\BUILDT~1\VC\Tools\MSVC\1427~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中的一个函数?
附:在 dll 中添加注册表函数并通过它传递 get_e 的想法是感谢,但在我的实际情况下无法考虑。
【问题讨论】: