【发布时间】:2021-04-25 06:52:12
【问题描述】:
我正在尝试创建一个非常简单的 dll 并将其加载到另一个文件以用于学习目的。我对 DLL 和 C++ 文件使用相同版本的 VC++。这是我的源代码:
加载.cpp:
#include <iostream>
#include <windows.h>
using namespace std;
typedef int(__stdcall* nsum)(int a, int b);
int main(void)
{
HINSTANCE myDll = LoadLibrary(L".\\DLL1.dll");
nsum sum = (nsum)GetProcAddress(myDll, "sum");
if (!myDll) {
cout << "could not load the dynamic library" << endl;
return EXIT_FAILURE;
}
int xfinal = sum(10, 20);
cout << xfinal << endl;
return 0;
}
和 dll.cpp
#include <windows.h>
#include "pch.h"
using namespace std;
int __declspec(dllexport) __stdcall sum(int a, int b)
{
return a + b;
}
pch.h
// pch.cpp: source file corresponding to the pre-compiled header
#include "pch.h"
// When you are using pre-compiled headers, this source file is necessary for compilation to succeed.
但我仍然遇到异常。我搜索了答案,但没有找到,所以我写这个寻求帮助
在 load.cpp 中,在 HINSTANCE myDll 中,我可以窥视并看到设置为 0x000000000 的值。是这个原因吗?如果是这样,我该如何解决?
【问题讨论】:
-
为什么会在 0x00000000 处抛出异常异常 0x00000000 通常不是要写入的有效地址。 (它是为
nullptr“保留”的。)因此,您可能无法读取或写入它(或者操作系统会因访问冲突而中止您的应用程序)。 -
@Scheff 那么我应该怎么做才能解决它?
-
顺便说一句。您首先使用
myDll,然后检查它的有效性。如果myDll无效,您的应用程序将在检查前终止。您应该在调试器中检查这是根本问题还是还有其他问题。 -
@Scheff 你能指导我如何检查吗?是不是像调试一样?
-
@Mayukh "你能指导我如何检查吗?"在
myDll的任何其他用法之前移动if (!myDll) {。
标签: c++ visual-studio visual-c++