一个数组A,一个数组B,大小和类型都相同,现在要交换其中对应位置的元素,如何在VB中最快速。
代码如下
Private Declare Function VarPtrArray Lib "msvbvm50" Alias "VarPtr" (Ptr() As Any) As Long Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpDst As Any,lpSrc As Any,ByVal ByteLength As Long) Private Sub Swap(a() As Long,b() As Long) Dim SafeA As Long,SafeB As Long Dim AddressA As Long,AddressB As Long CopyMemory SafeA,ByVal VarPtrArray(a),4 '得到指向A数组SAFEARRAY指针的指针 CopyMemory SafeB,ByVal VarPtrArray(b),4 '得到指向B数组SAFEARRAY指针的指针 SafeA = SafeA + 12 '偏移12个字节为指向真数组的指针 SafeB = SafeB + 12 CopyMemory AddressA,ByVal SafeA,4 '得到A数组的“真数组”的内存首地址 CopyMemory ByVal SafeA,ByVal SafeB,4 '交换B数组和A数组对应的真数组的内存首地址 CopyMemory ByVal SafeB,AddressA,4 End Sub