首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VB >

请各位看下,为什么 这段麻烦会报内存异常

2012-02-06 
请各位看下,为什么 这段麻烦会报内存错误这是正确的:VB codePublic Function AddVar(Dat() As Byte, Count

请各位看下,为什么 这段麻烦会报内存错误
这是正确的:

VB code
Public Function AddVar(Dat() As Byte, Count As Long, ByVal Var As Variant)Dim Ty As VbVarTypeDim Vint As IntegerDim Vlng As LongDim Vsin As SingleDim Vdub As DoubleTy = VarType(Var)If Ty = vbByte Then    ReDim Preserve Dat(Count)    Dat(Count) = Var    Count = Count + 1ElseIf Ty = vbInteger Then    Vint = Var    ReDim Preserve Dat(Count + LenB(Vint) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal VarPtr(Vint), LenB(Vint)    Count = Count + LenB(Vint)ElseIf Ty = vbVLong Then    Vlng = Var    ReDim Preserve Dat(Count + LenB(Vlng) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal VarPtr(Vlng), LenB(Vlng)    Count = Count + LenB(Vlng)ElseIf Ty = vbSingle Then    Vsin = Var    ReDim Preserve Dat(Count + LenB(Vsin) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal VarPtr(Vsin), LenB(Vsin)    Count = Count + LenB(Vsin)ElseIf Ty = vbDouble Then    Vdub = Var    ReDim Preserve Dat(Count + LenB(Vdub) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal VarPtr(Vdub), LenB(Vdub)    Count = Count + LenB(Vdub)End IfEnd Function




下面这个是错误的
VB code
Public Function AddVar(Dat() As Byte, Count As Long, ByVal Var As Variant)Dim Ty As VbVarTypeDim Vint As IntegerDim Vlng As LongDim Vsin As SingleDim Vdub As DoubleTy = VarType(Var)If Ty = vbByte Then    ReDim Preserve Dat(Count)    Dat(Count) = Var    Count = Count + 1ElseIf Ty = vbInteger Then    Vint = Var    ReDim Preserve Dat(Count + LenB(Vint) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal Vint, LenB(Vint)    Count = Count + LenB(Vint)ElseIf Ty = vbVLong Then    Vlng = Var    ReDim Preserve Dat(Count + LenB(Vlng) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal Vlng, LenB(Vlng)    Count = Count + LenB(Vlng)ElseIf Ty = vbSingle Then    Vsin = Var    ReDim Preserve Dat(Count + LenB(Vsin) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal Vsin, LenB(Vsin)    Count = Count + LenB(Vsin)ElseIf Ty = vbDouble Then    Vdub = Var    ReDim Preserve Dat(Count + LenB(Vdub) - 1)    CopyMemory ByVal VarPtr(Dat(Count)), ByVal Vdub, LenB(Vdub)    Count = Count + LenB(Vdub)End IfEnd Function




  这是两段代码唯一的不同为什么我加上了VarPtr就行呢????
  CopyMemory ByVal VarPtr(Dat(Count)), ByVal VarPtr(Vlng), LenB(Vlng)
  CopyMemory ByVal VarPtr(Dat(Count)), ByVal Vlng, LenB(Vdub)

  下面这段MoveMemory 是代码也是正确的,也没有加上VarPtr
  MoveMemory U_CmdS(Index), U_CmdS(Index + 1), (U_Count - Index - 1) * Len(U_AutoCmd)


求指教谢谢

[解决办法]
问题在于你的CompyMemory的声明上面

参阅

重点看看CopyMemory的声明
[解决办法]
VarPtr是读取变量的地址,而CopyMemory需要传入的是地址,所以,必须加上VarPtr

热点排行