Your DLL can create new SAFEARRAYs. When you create a new array, you should use a local variable rather than modify a passed-in array pointer. Once the allocation and any subsequent operations on the array are successful, you can assign the passed-in pointer to the local pointer and return from the function.
The following example accepts an array pointer and creates an array containing 10 integer elements:
short WINAPI NewArray(LPSAFEARRAY *ppsa)
{
LPSAFEARRAY psa;
SAFEARRAYBOUND sa;
sa.lLbound = 1;
sa.cElements = 10;
if (*ppsa == NULL) //array not yet initialized
{
if ((psa = SafeArrayCreate(VT_I2, 1, &sa)) == NULL)
return -2;
*ppsa = psa;
}
if ((*ppsa)->cDims != 1) // check array dimensions
return -1;
else return -3;
return 0;
}
Declared and called from Visual Basic:
Declare Function NewArray Lib "debug\ADVDLL.DLL" _
(a() As Integer) As Integer
Sub NewArrayTest()
Dim a(1) As Integer
Dim b() As Integer
MsgBox NewArray(a) & ":" & LBound(a) & ":" & UBound(a)
MsgBox NewArray(b) & ":" & LBound(b) & ":" & UBound(b)
End Sub