使用CopyMemory的问题
网上看到一段代码,拷贝下来实验,
多次运行,停止,运行,停止.然后退出vb,就报个错误出来
请高手帮忙看下!
代码如下:
'两个窗体Form1,Form2
'Form1
Option Explicit
Private Declare Function ArrayPtr Lib "msvbvm60 " Alias "VarPtr " (Ptr() As Any) As Long
Private Type PointSingle
a1 As String
a2 As String
End Type
Dim P(1) As PointSingle
Private Sub Form_Load()
P(0).a1 = "士大夫 "
P(0).a2 = "大会如同 "
P(1).a1 = "如同机 "
P(1).a2 = "是 "
Form2.Show
Form2.Draw ArrayPtr(P())
End Sub
-----------------------------------------------
'Form2
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32 " Alias "RtlMoveMemory " (ByVal lpDest As Long, ByVal lpSrc As Long, ByVal Length As Long)
Private Declare Function ArrayPtr Lib "msvbvm60 " Alias "VarPtr " (Ptr() As Any) As Long
Private Type PointSingle
a1 As String
a2 As String
End Type
Private Type SAFEARRAY1D
cDims As Integer
fFeatures As Integer
cbElements As Long
cLocks As Long
pvData As Long
cElements As Long
lLbound As Long
End Type
Dim P() As PointSingle
Public Sub Draw(lpPoints As Long)
Dim SA As SAFEARRAY1D
Dim pSA As Long
CopyMemory VarPtr(pSA), lpPoints, 4
CopyMemory VarPtr(SA), pSA, Len(SA)
With SA
If .cDims <> 1 Then Exit Sub
ReDim P(.lLbound To .lLbound + .cElements - 1)
CopyMemory VarPtr(P(.lLbound)), .pvData, .cbElements * .cElements
End With
AutoRedraw = True
Dim i As Long
For i = LBound(P) To UBound(P)
Debug.Print P(i).a1, P(i).a2
Next
End Sub
[解决办法]
不知道lZ打算干嘛,这么写漏洞太多了,首先数组里存放了字符串,字符串在内存里是先分配再使用的,A变量引用的字符串 又直接被拷贝到B,程序结束的时候会释放A、B字符串的内存空间,假如先释放B,然后释放A的时候由于指向同一内存,释放必定发生内存错误
SafeArray也是同样的道理,你的做法不仅会发生错误,而且造成内存泄露
[解决办法]
这不是 C++,不要随便用直接内存拷贝,vb里就用数组做循环拷贝,性能不高是VB的劣根性,没办法的,而且你干嘛必须用数组拷贝呢,如果是测试使用的话,那就不要试了
[解决办法]
友情帮顶一下!
[解决办法]
CopyMemory VarPtr(pSA), byval lpPoints, 4 不是复制内容?不同结构复制地址啥用?
[解决办法]
调用的地方,放在 Button 的事件里呢?