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

标签 c++ visual-studio-2008 dll dllimport

我在 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/

相关文章:

c++ - 如何从进程中获取实时、非阻塞的输出

asp.net-mvc - Resharper (R#) 4.5 和 MVC (1.0) 解决方案导致 Visual Studio 2008 SP1 在加载解决方案时崩溃

visual-studio-2008 - CMake 为 Win32 和 x64 生成 Visual Studio 2008 解决方案

c# - 单元测试的编写标准

c++ - 与 Windows 投影文件系统 DLL/LIB 链接

c++ - 从 Node JS 访问用 C++ 编写的设备 SDK

c++ - 如何为给定的int找到最近的偶数? (给定 11 返回 12)

c++ - 我可以将 dll 加载到共享内存中吗?

c++ - 使用 boost::interprocess::shared_ptr 共享生命周期跨进程

Python,使用 ctypes 创建 C++ 类包装器