Using User-Defined Data Structures

The Type statement in Visual Basic can be used to create user-defined data structures. For example, the following Visual Basic data type and C-language structure are equivalent.

In Visual Basic:

Type ARG
    i as Integer
    str as String
End Type

In C:

typedef struct 
{
    short i;
    BSTR str;
} ARG;

User-defined data types cannot be passed by value; they must be passed by reference. Your C function should declare the argument as a pointer to the structure. If the structure contains BSTR values (as this example does), the rules discussed above apply to those values; you must test the BSTR before you reassign it (and free it if it is already allocated). You should not manipulate it directly.

For example, this C-language function fills a structure with a string and the length of the string:

short WINAPI StructArg(ARG *parg, char *szArg)
{
    BSTR bstr;

    if (parg == NULL)
        return -1;

    // allocate a local string first; if this fails, 
    // we have not touched the passed-in string
    
    if ((bstr = SysAllocString((BSTR)szArg)) == NULL)
        return -1;

    if (parg->bstr != NULL)    // string is already assigned
        SysFreeString(parg->bstr);

    parg->i = SysStringByteLen(bstr);
    parg->bstr = bstr;

    return parg->i;
}

Declared and called from Visual Basic:

Declare Function StructArg Lib "debug\ADVDLL.DLL" _
    (a As ARG, ByVal s As String) As Integer

Sub StructArgTest()
    Dim x As ARG
    MsgBox StructArg(x, "abracadabra")
    MsgBox x.str & ":" & str$(x.i) 'displays string and length
End Sub