Visual Studio C++: When should I be using __declspec(dllimport)?(Visual Studio C++:我什么时候应该使用 __declspec(dllimport)?)
问题描述
我有一个关于在 Visual Studio 2005 及更高版本中构建/链接 DLL 的问题.基本上我的理解和经验是这样的:
I had a question about DLL building / linking in Visual Studio 2005 and later. Basically my understanding and experience is this:
为了构建一个 DLL,我指定了项目属性来构建一个 DLL,然后在我想从 DLL 中公开暴露的任何函数或成员的前面加上 __declspec(dllexport).构建项目将产生一个 DLL、一个 Lib 和一个头文件,这些文件可以部署为 API 或其他东西.
To build a DLL, I specify the project properties to build a DLL, and then I but __declspec(dllexport) in front of any functions or members that I want to publically expose from the DLL. Building the project will result in a DLL, a Lib, and a header file that can be deployed as say an API or something.
另一方面,要让其他已编译的可执行应用程序动态链接到 DLL 并使用其函数,您只需让可执行项目包含头文件并链接到 DLL 时创建的小 lib 文件被建.只要编译后的应用程序能找到 DLL,一切都会好起来的.
On the other end, to have your other compiled executable application dynamically link to the DLL and use its functions, you simply need to have your executable project include the header files and link with the small lib file that was created when the DLL was built. As long and the compiled application can find the DLL, everything will work.
这是我的经验,也是 Microsoft DLL 构建教程在 MSDN 上描述所有内容的方式.我想知道:这是标准做法吗?你什么时候需要在任何地方使用 __declspec(dllimport) ?我错过了什么吗?
That has been my experience and that is also how the Microsoft DLL building tutorial described everything on MSDN. I am wondering: is this standard practice? When would you ever need to use __declspec(dllimport) anywhere? Am I missing something?
谢谢!
推荐答案
是的,你会使用 __declspec(dllimport) 并且你通常有一个宏来控制源文件是导出(如果它是你的 DLL 的一部分)还是导入(如果它是 using-executable) 符号的一部分.
Yes you would use __declspec(dllimport) and you generally have a macro that controls whether a source file either exports (if it's part of your DLL) or imports (if it's part of the using-executable) symbols.
在您的 DLL 中,您可以将清单常量设置为某种构建设置,比如BUILDING_MY_DLL",然后在您的头文件中创建这样的宏:
In your DLL you can set a manifest constant to the build settings of some sort, say 'BUILDING_MY_DLL' and then create the macro like this within your header file:
#ifdef BUILDING_MY_DLL
#define MY_DLL_EXPORT __declspec(dllexport)
#else
#define MY_DLL_EXPORT __declspec(dllimport)
#endif
然后像这样装饰你的导出函数:
and then decorate your exported functions like this:
MY_DLL_EXPORT int func(int y);
您也可以通过这种方式导出整个类:
You can also export entire classes this way too:
class MY_DLL_EXPORT InterestingClass
{
...
};
这篇关于Visual Studio C++:我什么时候应该使用 __declspec(dllimport)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Visual Studio C++:我什么时候应该使用 __declspec(dllimport)?
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01