为什么要使用DllImport属性的结合在添加引用? [英] Why use DllImport Attribute as apposed to adding a reference?

查看:341
本文介绍了为什么要使用DllImport属性的结合在添加引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过几个象这样的例子:

 函数[DllImport(user32.dll中)] 
上配置静态的extern BOOL的TranslateMessage([IN]参考消息LPMSG);

函数[DllImport(user32.dll中)]
静态外部的IntPtr在DispatchMessage([IN]参考消息LPMSG);



不过,我不明白的是为什么会有人做,因为并列只是引用的DLL像他们这样做其他图书馆? MSDN的指出:在重复使用托管应用程序的现有非托管代码时,DllImport属性是非常有用的,例如,您的托管应用程序可能需要对非托管WIN32 API调用。但是,是说它不是引用一个非托管的DLL或无法以其他方式?


有用
解决方案

不过,是说这是没有用的
引用一个非托管的DLL或
,否则不可能?




是的,正是如此。你在想什么,因为引用一个DLL实际上是引用一个.NET程序集 - 它只是恰巧,包装的那种组件人们往往引用的最常用的方法是在DLL



dllimport的完全是有关导入传统的DLL - 即那些其出口使用原始的Windows DLL导出机制,所有的方法



想想dllimport的作为实际上被称为UnmanagedImport',事情可能会更清晰。


I've seen a couple of examples such as this:

[DllImport("user32.dll")]
static extern bool TranslateMessage([In] ref Message lpMsg);

[DllImport("user32.dll")]
static extern IntPtr DispatchMessage([In] ref Message lpmsg);

But, what I don't understand is why someone would do that as apposed to just referencing the DLL like they do other libraries? The MSDN states: "The DllImport attribute is very useful when reusing existing unmanaged code in a managed application. For instance, your managed application might need to make calls to the unmanaged WIN32 API." But, is that saying it is not useful to reference an unmanaged dll or impossible otherwise?

解决方案

"But, is that saying it is not useful to reference an unmanaged dll or impossible otherwise?"

Yes, exactly so. What you're thinking of as 'referencing a DLL' is actually 'referencing a .NET assembly' - it just so happens that the most common way of packaging the kind of assemblies one tends to reference is in a DLL.

DLLImport is entirely about importing 'traditional DLLs' - i.e. ones which export all their methods using the original Windows DLL export mechanism.

Think of DLLImport as actually being called 'UnmanagedImport', and things might be clearer.

这篇关于为什么要使用DllImport属性的结合在添加引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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