Array as a Class Member

后端 未结 3 832
醉话见心
醉话见心 2021-01-02 06:57

I\'m designing a dynamic buffer for outgoing messages. The data structure takes the form of a queue of nodes that have a Byte Array buffer as a member. Unfortunately in VB

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 07:32

    So it turns out I needed a little help from OleAut32.dll, specifically the 'VariantCopy' function. This function faithfully makes an exact copy of one Variant to another, including when it is ByRef!

    'clsTest
    
    Private Declare Sub VariantCopy Lib "OleAut32" (pvarDest As Any, pvargSrc As Any)
    
    Private m_Buffer() As Byte
    
    Public Property Let Buffer(buf As Variant)
        m_Buffer = buf
    End Property
    
    Public Property Get Buffer() As Variant
        Buffer = GetByRefVariant(m_Buffer)
    End Property
    
    Private Function GetByRefVariant(ByRef var As Variant) As Variant
        VariantCopy GetByRefVariant, var
    End Function
    

    With this new definition, all the tests pass!

    'mdlMain
    
    Public Sub Main()
        Dim buf() As Byte
        ReDim buf(0 To 4)
    
        buf(0) = 1
        buf(1) = 2
        buf(2) = 3
        buf(3) = 4
    
    
        Dim oBuffer As clsTest
        Set oBuffer = New clsTest
    
        'Test #1, the assignment
        oBuffer.Buffer = buf    'Success!
    
        'Test #2, get the value of an index in the array
        Debug.Print oBuffer.Buffer()(2)    'Success!  This is from GSerg's comment on the question
    
        'Test #3, change the value of an index in the array and verify that it is actually modified
        oBuffer.Buffer()(2) = 27
        Debug.Print oBuffer.Buffer()(2)  'Success! Diplays "27" in the immediate window
    End Sub
    

提交回复
热议问题