views:

978

answers:

2

I notice in the MSDN documentation that there are multiple ways to declare a reference to a function in an external DLL from within a VB.NET program.

The confusing thing is that MSDN claims that you can only use the DllImportAttribute class with Shared Function prototypes "in rare cases", but I couldn't find the explanation for this statement, while you can simply use the Declare keyword instead.

Can any of the .NET gurus explain to me why these are different, and where I would appropriately use each case? I greatly appreciate the help :)

+4  A: 

Declare is really an attempt to maintain a PInvoke syntax which would be more familiar to VB6 users converting to VB.Net. It has many of the same features as PInvoke but the marshalling of certain types, in particular strings, are very different and can cause a bit of confusion to people more familiar with DllImport rules.

I'm not entirely sure what the documentation is alluding to with the "rare" distinction. I use DllImport in my code frequently from both VB.Net and C# without issue.

In general, I would use DllImport over Declare unless you come from a vb6 background. The documentation and samples for DllImport are much better and there are many tools aimed at generating DllImport declarations.

JaredPar
A: 

For my opinion since this keyword doesn't look deprected etc. from what I searched, why not simply use compile-time keywords rather than attributes?

Also, when you use the Declare, you don't need to write the End Function. The advantage of that is that you can create a whole module of declarations of function imports line by line, no need to spend lines for DllImports and End Functions.

When you declare using the Declare keyword, the compiler treats this function as Shared anyway, so it can be accessed via other extenal objects.

But I think in current vb.net they're both addressed to the same target and no performance difference - no warranty on this one.

So my conclusion is Do use the Declare instead of DllImport, especially reading what you quotet that Microsoft stated that it should be used in rare cases.

Shimmy