VB10 vs VB6: ByVal/ByRef within API calls.
This is part of series of posts categorized under VB10 vs VB6.
“Use of ByVal/ByRef directly within API calls is not supported.”
Huh?
1
2
3
Declare Function SetEnvironmentVariable Lib "kernel32" Alias "SetEnvironmentVariableA" ( _
ByVal lpName As String,
ByVal lpValue As String) As Boolean
The above code is syntactically correct in VB6 and VB10. Notice the inclusion of the word ByVal
. You could use ByRef
as well. Additionally, VB10 offers a plethora of additional options that allow you to further define how things are passed to various api implementations. So the above statement could be written as:
1
2
3
Declare Auto Function SetEnvironmentVariable Lib "kernel32" Alias "SetEnvironmentVariableA" (
<MarshalAsAttribute(UnmanagedType.LPStr)> ByVal lpName As String,
<MarshalAsAttribute(UnmanagedType.LPStr)> ByVal lpValue As String) As Boolean
This will cause the strings to be passed as a long pointer to a string instead of a BStr
. Additionally, the Auto
keyword will cause the Interop process to use ANSI or Unicode strings depending on the target API.
What I’m showing here just scratches the surface of what VB10 can do regarding operating with the Windows API’s. In any case, the ByVal
keyword is definitely there, so I’m not sure what Karl is trying to say with this one.
Verdict
The statement that ByVal
and ByRef
are not supported is obviously false so I have to give this one to VB10.
Update(s)
Bill McCarthy (MVP) writes in: “Again my memory is getting rusty, but I think this refers to the use of As Any, then you could pass a variable out ByRef
or ByVal
. Often the cause of many mistakes hard to track down as a variable address would be sent instead of the value etc.”
Bill apparently agrees with me regarding “As Any” being a “bad thing”. ;-) He does bring up a good point regarding ByRef
/ByVal
from the perspective of “how” Interop works in .NET (thus VB10). Win32 API signatures as defined in VB most likely will not be identical in behavior with the move to VB10. With that said, using a site such as http://pinvoke.net/ to verify your signatures is the first thing that I would suggest. Yes, this means that the trusty Win32 API book by Dan Appleman is a little out of date; however, it’s just the “signatures” that have to be dealt with since the .NET variety offers the granular level required to enable you to access all of the API available.