使用DLL文件加载函数时,函数报错说找不到指定的程序:
#include <iostream>
#include <Windows.h>
#include <string>
#include <comdef.h>
using namespace std;
int main()
{
try {
static HMODULE hmGHSL = LoadLibrary(L"GSHL.dll");
if (hmGHSL == nullptr) {
throw GetLastError();
}
static std::string(*fLoadFileFunction)(std::string) =
reinterpret_cast<std::string(*)(std::string)>(GetProcAddress(hmGHSL, "GetFile"));
if (fLoadFileFunction == nullptr) {
throw GetLastError();
}
fLoadFileFunction("Null");
}
catch (DWORD& hr) {
//获取错误信息并输出
_com_error err(hr);
std::wstring desc = err.ErrorMessage();
MessageBox(GetConsoleWindow(), desc.c_str(), L"", MB_OK);
}
catch (const char* c) {
MessageBoxA(GetConsoleWindow(), c, "", MB_OK);
}
}
程序的结果为:
GSHL.dll:
function.cpp:
#include "pch.h"
#include <iostream>
#include <vector>
#include <map>
/*作用:获得编译入DLL文件GSHL.dll的文件的字符串形式
* 参数:
* 1.文件的名称
*/
std::string __declspec(dllexport) GetFile(std::string filename) {
//以下是声明
static std::map<std::string, std::vector<int>> filemap = {
{"Null",{0}}
};
//函数返回
std::vector<int> a = filemap[filename];
if (a.size() == 0) throw "File not found.";
std::string res;
for (int c : a) {
res += (char)c;
}
return res;
}
pch.h
// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H
pch.cpp
// pch.cpp: 与预编译标头对应的源文件
#include "pch.h"
// 当使用预编译的头时,需要使用此源文件,编译才能成功。
dllmain.cpp:
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
framework.h:
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>