Visual Studio C++:我什么时候应该使用 __declspec(dllimport)?
我有一个关于在 Visual Studio 2005 及更高版本中构建/链接 DLL 的问题。基本上我的理解和经验是这样的:
要构建 DLL,我指定项目属性来构建 DLL,然后在我想要从 DLL 公开公开的任何函数或成员前面添加 __declspec(dllexport) 。构建项目将生成一个 DLL、一个 Lib 和一个头文件,可以将其部署为 API 或其他文件。
另一方面,要让其他已编译的可执行应用程序动态链接到 DLL 并使用其功能,您只需让可执行项目包含头文件并链接到构建 DLL 时创建的小 lib 文件。只要编译后的应用程序可以找到 DLL,一切都会正常。
这是我的经验,也是 Microsoft DLL 构建教程在 MSDN 上描述所有内容的方式。我想知道:这是标准做法吗?什么时候你需要在任何地方使用 __declspec(dllimport) ?我错过了什么吗?
谢谢!
I had a question about DLL building / linking in Visual Studio 2005 and later. Basically my understanding and experience is this:
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.
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.
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?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您会使用 __declspec(dllimport) 并且通常有一个宏来控制源文件是导出(如果它是 DLL 的一部分)还是导入(如果它是 using-executable 的一部分)符号。
在 DLL 中,您可以将清单常量设置为某种类型的构建设置,例如“BUILDING_MY_DLL”,然后在头文件中创建如下宏:
然后像这样装饰导出的函数:
您还可以通过这种方式导出整个类也:
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.
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:
and then decorate your exported functions like this:
You can also export entire classes this way too: