gpt4 book ai didi

c++ - 从 C++ 调用 DLL 中的函数

转载 作者:IT老高 更新时间:2023-10-28 12:30:12 32 4
gpt4 key购买 nike

我在 VS 2008 中有一个解决方案,其中包含 2 个项目。一个是用 C++ 编写的 DLL,另一个是从空白项目创建的简单 C++ 控制台应用程序。我想知道如何从应用程序调用 DLL 中的函数。

假设我从一个空白 C++ 项目开始,并且我想调用一个名为 int IsolatedFunction(int someParam)

的函数

我怎么调用它?

最佳答案

有很多方法可以做到这一点,但我认为最简单的选择之一是在链接时将应用程序链接到 DLL,然后使用 定义文件 来定义要从中导出的符号DLL。

CAVEAT:定义文件方法最适合未修饰符号名称。如果你想导出修饰符号,那么最好不使用定义文件方法。

这里有一个简单的例子说明如何做到这一点。

第一步:export.h文件中定义函数。

int WINAPI IsolatedFunction(const char *title, const char *test);

第二步:export.cpp文件中定义函数。

#include <windows.h>

int WINAPI IsolatedFunction(const char *title, const char *test)
{
MessageBox(0, title, test, MB_OK);
return 1;
}

第 3 步:将函数定义为 export.def 定义文件中的导出。

EXPORTS    IsolatedFunction          @1

步骤 4: 创建一个 DLL 项目并将 export.cppexport.def 文件添加到该项目中。构建这个项目将创建一个 export.dll 和一个 export.lib 文件。

以下两个步骤在链接时链接到 DLL。如果您不想在链接时定义入口点,请忽略接下来的两个步骤,并使用 LoadLibraryGetProcAddress 在运行时加载函数入口点。

第 5 步:通过将 export.lib 文件添加到项目中来创建一个 Test 应用程序项目以使用 dll。将 export.dll 文件复制到与 Test 控制台可执行文件相同的位置。

第 6 步:从 Test 应用程序中调用 IsolatedFunction 函数,如下所示。

#include "stdafx.h"

// get the function prototype of the imported function
#include "../export/export.h"

int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// call the imported function found in the dll
int result = IsolatedFunction("hello", "world");

return 0;
}

关于c++ - 从 C++ 调用 DLL 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/539358/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com