Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays as parameters in VB6

The following code kills VB6 (sp6) with an 'unhandled exception fault in VB.exe' on two machines in the office on the line marked.

''# Form1.frm
Option Explicit
Private ArrayHolder As Class2

Private Sub Command1_Click()
    Set ArrayHolder = New Class2

    Dim arr(3) As Long
    arr(0) = 1
    arr(1) = 2
    arr(2) = 3

    ArrayHolder.Add arr

End Sub

''# -----------------------------------------------------------    
''# Class1.cls
Option Explicit

Private m_myArray() As Long

Public Property Get myArray() As Long()
    myArray = m_myArray
End Property

Friend Property Let myArray(ByRef anArray() As Long)
    m_myArray = anArray
End Property

''# -----------------------------------------------------------    
''# Class2.cls
Option Explicit

Friend Function Add(newArray() As Long) As Class1
    Dim oClass As Class1
    Set oClass = New Class1

    oClass.myArray = newArray  <- This kills VB6 dead
    MsgBox "passed"

End Function

From what I can tell on various websites I am passing an array correctly but am I actually doing it correctly, and why is it causing VB6 to die so horribly?

like image 354
graham.reeds Avatar asked May 12 '09 12:05

graham.reeds


3 Answers

I don't have an answer, and certainly is a curious question, but why don't just add a method and move on?

'Passed the test
Public Sub LetMyArray(anArray() As Long)
    m_myArray = anArray
End Sub


'oClass.MyArray = newArray ' <- This kills VB6 dead
oClass.LetMyArray newArray  ' <- This works
like image 140
Eduardo Molteni Avatar answered Sep 20 '22 14:09

Eduardo Molteni


This is a bug in the IDE (compiled is ok) that MS never fixed. I'm using a workaround with a temp array like this:

Friend Function Add(newArray() As Long) As Class1
    Dim oClass As Class1
    Dim tempArray() As Long
    Set oClass = New Class1

    tempArray = newArray
    oClass.myArray = tempArray <- Should work now
    MsgBox "passed"

End Function

FYI, it gets worse with Byte arrays (Long arrays are safe) when you accidentally hover with the mouse over the param or the array property. Better keep your mouse away from the code :-))

like image 28
wqw Avatar answered Sep 17 '22 14:09

wqw


I have no idea why this happens, but if you anyway want a copy of an array, use a Variant in class2:

Private m_myArray As Variant

Public Property Get myArray() As Variant
    myArray = m_myArray
End Property

Friend Property Let myArray(anArray As Variant)
    m_myArray = anArray
End Property

Fixes it, but still, I'm curious about the reason.

like image 43
GSerg Avatar answered Sep 20 '22 14:09

GSerg