从 C++ 调用 DLL 中的函数
我在 VS 2008 中有一个解决方案,其中包含 2 个项目.一个是用 C++ 编写的 DLL,另一个是从空白项目创建的简单 C++ 控制台应用程序.我想知道如何从应用程序调用 DLL 中的函数.
I have a solution in VS 2008 with 2 projects in it. One is a DLL written in C++ and the other is a simple C++ console application created from a blank project. I would like know how to call the functions in the DLL from the application.
假设我从一个空白的 C++ 项目开始,我想调用一个名为 int IndependentFunction(int someParam)
Assume I am starting with a blank C++ project and that I want to call a function called int IsolatedFunction(int someParam)
我怎么称呼它?
推荐答案
有很多方法可以做到这一点,但我认为最简单的选择之一是在链接时将应用程序链接到 DLL,然后使用 定义文件来定义要从DLL中导出的符号.
There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.
警告:定义文件方法最适合未修饰符号名称.如果您想导出装饰符号,那么最好不要使用定义文件方法.
CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.
这是一个简单的例子,说明如何做到这一点.
Here is an simple example on how this is done.
步骤 1: 在 export.h 文件中定义函数.
Step 1: Define the function in the export.h file.
int WINAPI IsolatedFunction(const char *title, const char *test);
第 2 步:在 export.cpp 文件中定义函数.
Step 2: Define the function in the export.cpp file.
#include <windows.h>
int WINAPI IsolatedFunction(const char *title, const char *test)
{
MessageBox(0, title, test, MB_OK);
return 1;
}
步骤 3: 在 export.def 定义文件中将函数定义为导出.
Step 3: Define the function as an export in the export.def defintion file.
EXPORTS IsolatedFunction @1
步骤 4: 创建一个 DLL 项目并将 export.cpp 和 export.def 文件添加到该项目中.构建此项目将创建一个 export.dll 和一个 export.lib 文件.
Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.
以下两个步骤在链接时链接到 DLL.如果您不想在链接时定义入口点,请忽略接下来的两个步骤并使用 LoadLibrary 和 GetProcAddress 在运行时加载函数入口点.
The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.
第 5 步:通过将 export.lib 文件添加到项目中,创建一个 Test 应用程序项目以使用该 dll.将 export.dll 文件复制到与 Test 控制台可执行文件相同的位置.
Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.
第 6 步:从测试应用程序中调用 IsolatedFunction 函数,如下所示.
Step 6: Call the IsolatedFunction function from within the Test application as shown below.
#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;
}
相关文章