Visual Studio C ++:我什么时候应该使用__declspec(dllimport)? [英] Visual Studio C++: When should I be using __declspec(dllimport)?

查看:161
本文介绍了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,然后我在__declspec(dllexport)前面任何函数或成员,我想从DLL公开暴露。构建项目将产生一个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的一部分)或导入(如果它是使用可执行)的符号。

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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆