Passing Arguments by Reference

By default, Visual Basic passes arguments by reference, rather than by value. If your function expects a pointer, you should pass ByRef; otherwise pass ByVal. Strings are an exception to this rule. When you pass a string ByVal you are passing a pointer to the string. If you pass a string ByRef you are passing a pointer to a pointer to a string.

For example, this C-language function modifies its argument by multiplying it by two. The function returns False if the argument is less than zero.

BOOL WINAPI PointerArg(short *pn)
{
    if (*pn < 0)
        return 0;    // False in Visual Basic
        
    *pn *= 2;
    return -1;        // True in Visual Basic
}

The Visual Basic declaration for this function does not include the ByVal keyword. You may include the ByRef keyword, but it isn't necessary. It is a good idea to explicitly include the ByRef keyword for clarity. Most problems with declarations have to do with a confusion over whether to pass ByRef or ByVal.

Declare Function PointerArg Lib "debug\ADVDLL.DLL" _
    (ByRef d As Integer) As Boolean

Sub TestPointerArg()
    Dim n As Integer
    Dim r As Boolean

    n = CInt(InputBox("Number?"))
    r = PointerArg(n)
    MsgBox n & ":" & r
End Sub