在 c++ 中使用 dll 中的函数?
我在类名之前使用 __declspec(dllexport) 在 C++ 中创建了一个 dll。现在,当我尝试在另一个 C++ 程序中使用它时,它会崩溃。当我调试它时,我发现函数指针根本没有初始化。请帮助我。
using namespace std;
typedef void (*func)();
int main()
{
func funcpointer;
HINSTANCE xyz = LoadLibrary(TEXT("C:\\extra\\dll\\dlls\\debug\\random.dll"));
funcpointer = (func)GetProcAddress(xyz,"get it");
funcpointer();
return 0;
}
提前致谢。
I have created a dll in c++ using __declspec(dllexport) before class name. Now when i try to use it in another c++ program it crashes in between. When i debugged it i found that the function pointer is not initialized at all. help me plz.
using namespace std;
typedef void (*func)();
int main()
{
func funcpointer;
HINSTANCE xyz = LoadLibrary(TEXT("C:\\extra\\dll\\dlls\\debug\\random.dll"));
funcpointer = (func)GetProcAddress(xyz,"get it");
funcpointer();
return 0;
}
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先使用 DUMPBIN /EXPORTS yourdll.dll 来查看您希望导出的函数是否实际导出及其确切名称。如果您发现名称“mangled”,您可能需要将该函数声明为
extern "C"
。一旦你确定了名字,你走的路就是正确的。还要检查加载库后HINSTANCE xyz
是否变为非空。如果为 null,您可能无法到达 dll(不在搜索路径中),或者由于某种原因无法加载,例如因为缺少某些依赖项。First of all use
DUMPBIN /EXPORTS yourdll.dll
to see if the function you expect to be exported is actually exported and its exact name. If you find the name "mangled" you probably need to declare the function asextern "C"
. Once you have determined the name the way you go is correct. Check also theHINSTANCE xyz
became not null after loading the library. If null you robably don't reach the dll ( not in the search path ) or for some reason it can't load for example because some dependencies are missing.在检索到的函数的头文件中,您不仅应该有 dllexport,还应该有整个 dllexport/dllimport 定义:
您可以阅读 DLL 教程 了解更多详细信息。
You should have not only dllexport, but also the whole dllexport/dllimport definition in the retrieved function's header file:
You can read the DLL Tutorial for more details.
导出函数时使用 extern "C" fndecl。这将有助于获得未修饰的名称或使用 def 文件。要检查导出函数的名称,请使用工具 Dependency Walker (depends.exe)。
如果您有 C++ 类,我建议您链接到 DLL。使用 GetProcAddress 使用 C++ 类会很痛苦。
如果您不熟悉 DLL,那么您可能也会对这个链接感兴趣:
演练:创建和使用动态链接库
When you export your function use extern "C" fndecl. This will help to get an undecorated name or use a def-file. To check the name of the exported function use the tool Dependency Walker (depends.exe).
If you have a C++ class I would advise you to link to the DLL. Using GetProcAddress it would be a pain to use a C++ class.
This link could also be interesting for you if you are new to DLLs:
Walkthrough: Creating and Using a Dynamic Link Library