Visual Studio C++:我什么时候应该使用 __declspec(dllimport)?

发布于 2024-10-12 16:09:04 字数 435 浏览 6 评论 0原文

我有一个关于在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同展鸳鸯锦 2024-10-19 16:09:04

是的,您会使用 __declspec(dllimport) 并且通常有一个宏来控制源文件是导出(如果它是 DLL 的一部分)还是导入(如果它是 using-executable 的一部分)符号。

在 DLL 中,您可以将清单常量设置为某种类型的构建设置,例如“BUILDING_MY_DLL”,然后在头文件中创建如下宏:

#ifdef BUILDING_MY_DLL
#define MY_DLL_EXPORT __declspec(dllexport)
#else
#define MY_DLL_EXPORT __declspec(dllimport)
#endif

然后像这样装饰导出的函数:

MY_DLL_EXPORT int func(int y);

您还可以通过这种方式导出整个类也:

class MY_DLL_EXPORT InterestingClass
{
...
};

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:

#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
{
...
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文