'当然少不了的CopyMemory,不用ANY的版本。
Declare Sub CopyMemory Lib "kernel32" Alias _
"RtlMoveMemory" (ByVal dest As Long, ByVal source As Long, _
ByVal numBytes As Long)
'嘿嘿,看下面是如何将CallWindowProc的声明做成Compare声明的。
Declare Function Compare Lib "user32" Alias _
"CallWindowProcA" (ByVal pfnCompare As Long, ByVal pElem1 As Long, _
ByVal pElem2 As Long, ByVal unused1 As Long, _
ByVal unused2 As Long) As Integer
'注:ByVal xxxxx As Long ,还记得吧!这是标准的指针声明方法。
'声明需要比较的数组元素的结构
Public Type TEmployee
Name As String
Salary As Currency
End Type
'再来看看我们的比较函数
'先按薪水比较,再按姓名比较
Function CompareSalaryName(Elem1 As TEmployee, _
Elem2 As TEmployee, _
unused1 As Long, _
unused2 As Long) As Integer
Dim Ret As Integer
Ret = Sgn(Elem1.Salary - Elem2.Salary)
If Ret = 0 Then
Ret = StrComp(Elem1.Name, Elem2.Name, vbTextCompare)
End If
CompareSalaryName = Ret
End Function
'先按姓名比较,再按薪水比较
Function CompareNameSalary(Elem1 As TEmployee, _
Elem2 As TEmployee, _
unused1 As Long, _
unused2 As Long) As Integer
Dim Ret As Integer
Ret = StrComp(Elem1.Name, Elem2.Name, vbTextCompare)
If Ret = 0 Then
Ret = Sgn(Elem1.Salary - Elem2.Salary)
End If
CompareNameSalary = Ret
End Function
最后再看看我们来看看我们最终的qsort的声明。
Sub qsort(ByVal ArrayPtr As Long, ByVal nCount As Long, _
ByVal nElemSize As Integer, ByVal pfnCompare As Long)
Sub qsort(ByVal ArrayPtr As Long, ByVal nCount As Long, _
ByVal nElemSize As Integer, ByVal pfnCompare As Long)
Dim i As Long, j As Long
'这里省略快速排序算法的具体实现,仅给出比较两个元素的方法。
If Compare(pfnCompare, ArrayPtr + (i - 1) * nElemSize, _
ArrayPtr + (j - 1) * nElemSize, 0, 0) > 0 Then
'如果第i个元素比第j个元素大则用CopyMemory来交换这两个元素。
End IF
End Sub