不能定义声明dllimport_DllImport与VB.NET中的声明

显然,Declare和DllImport语句基本相同。你可以使用任何你喜欢的。

以下是关于每一点可能有点不同的几点的讨论,这可能会影响到彼此的偏好:

我从MSDN的一篇关于Visual Studio 2003的文章开始,名为Using the DllImport Attribute。 (有点旧,但由于DllImport声明似乎源于.NET,所以似乎适合回到开头。)

给出一个DllImport语句的例子:

[DllImport("user32.dll", EntryPoint = "MessageBox", CharSet = Unicode)]

int MessageBox(void* hWnd, wchar_t* lpText, wchar_t* lpCaption, unsigned int uType);它说,如果EntryPoint值被省略,CLR将作为默认值查找函数的名称(在这种情况下为MessageBox)。但是,在这种情况下,由于指定了Unicode的CharSet,因此CLR将首先查找名为“MessageBoxW”的函数 - 指示Unicode返回类型的“W”。 (ANSI返回类型版本将为“MessageBoxA”。)如果没有找到“MessageBoxW”,那么CLR将查找实际称为“MessageBox”的API函数。

关于DllImportAttribute类的当前细节可以在这里找到,我查看了.NET Framework 4版本:DLLImportAttribute Class

此.NET Framework 4页的备注部分中的一条关键注释是:

You apply this attribute directly to C# and C++ method definitions; however, the Visual Basic compiler emits this attribute when you use the Declare statement.

所以,至少与VB.NET相关的是,编译器无论如何都会以Declare语句结束。

此页面中还有一个重要提示:

The DllImportAttribute does not support marshaling of generic types.

所以,看起来如果你想使用泛型类型,你必须使用Declare语句。

接下来,我转向了Declare语句信息。 Visual Studio 2010版本(Visual Basic语句信息)在这里:Declare Statement

这里的一个关键项目是这个笔记:

You can use Declare only at module level. This means the declaration context for an external reference must be a class, structure, or module, and cannot be a source file, namespace, interface, procedure, or block.

显然,如果您想在类,结构或模块外部设置API调用,则必须使用DllImport语句而不是Declare。

此页面上的示例Declare声明是:

Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" (

ByVal lpBuffer As String, ByRef nSize As Integer) As Integer接下来的例子就是这个小小的信息:

The DllImportAttribute provides an alternative way of using functions in unmanaged code. The following example declares an imported function without using a Declare statement.

其次是DllImport使用示例。

关于Unicode与ANSI的结果,根据这个Declare页面,如果您指定了一个CharSet值(在Declare中可用,但在上面的示例中未显示),CLR将执行与DllImport相同类型的自动名称搜索 - 对于Unicode或ANSI。

如果您在Declare语句中未指定CharSet值,那么您必须确保Declare中的函数名称与实际API函数头文件中的函数名称相同,或者您必须指定Alias值,该值与头文件中的实际函数名称(如上例所示)。

我无法找到任何具体的Microsoft文档,说明在上述以外的任何情况下,DllImport或Declare都是首选的,甚至是建议的。

因此,我的结论是:

1)除非你需要将你的定义放在一个Declare语句不能使用的地方,否则两种技术都可以正常工作,

2)如果你使用的是DllImport,请确保你指定了你想要的CharSet值(Unicode或ANSI),否则你可能会得到意想不到的结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值