'标准的做法SwapStr Sub SwapStr(sA As String, sB As String) Dim sTmp As String sTmp = sA: sA = sB: sB = sTmp End Sub |
'用指针的做法SwapPtr Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _ (Destination As Any, Source As Any, ByVal Length As Long) Sub SwapPtr(sA As String, sB As String) Dim lTmp As Long CopyMemory lTmp, ByVal VarPtr(sA), 4 CopyMemory ByVal VarPtr(sA), ByVal VarPtr(sB), 4 CopyMemory ByVal VarPtr(sB), lTmp, 4 End Sub |
[entry("VarPtr"), hidden] long _stdcall VarPtr([in] void* Ptr); [entry("VarPtr"), hidden] long _stdcall StrPtr([in] BSTR Ptr); [entry("VarPtr"), hidden] long _stdcall ObjPtr([in] IUnknown* Ptr); |
Private Declare Function ObjPtr Lib "MSVBVM60" Alias "VarPtr" (var As Object) As Long Private Declare Function VarPtr Lib "MSVBVM60" (var As Any) As Long |
long VarPtr(void* pv){ return (long)pv; } |
mov eax,dword ptr [esp+4] ret 4 '弹出栈里参数的值并返回。 |
'体会ByVal和ByRef Sub TestCopyMemory() Dim k As Long k = 5 Note: CopyMemory ByVal VarPtr(k), 40000, 4 Debug.Print k End Sub |
Note2: CopyMemory ByVal VarPtr(k), ByVal 40000, 4 |
Note3: CopyMemory VarPtr(k), 40000, 4 |
'看看我们的东西被拷贝到哪儿去了 Sub TestCopyMemory() Dim i As Long, k As Long k = 5 i = VarPtr(k) NOTE4: CopyMemory i, 40000, 4 Debug.Print k Debug.Print i i = VarPtr(k) NOTE5: CopyMemory ByVal i, 40000, 4 Debug.Print k End Sub |
5 40000 40000 |
struct POINT{ int x; int y; }; int Compare(void* elem1, void* elem2){} void PtrDemo(){ //指针声明: char c = 'X'; //声明一个char型变量 char* pc; long* pl; //声明普通指针 POINT* pPt; //声明结构指针 void* pv; //声明无类型指针 int (*pfnCastToInt)(void *, void*);//声明函数指针: //指针赋值: pc = &c; //将变量c的地址值赋给指针pc pfnCompare = Compare; //函数指针赋值。 //指针取值: c = *pc; //将指针pc所指处的内存值赋给变量c //用指针赋值: *pc = 'Y' //将'Y'赋给指针pc所指内存变量里。 //指针移动: pc++; pl--; } |
Type POINT X As Integer Y As Integer End Type Public Function Compare(elem1 As Long, elem2 As Long) As Long ' End Function Function FnPtrToLong(ByVal lngFnPtr As Long) As Long FnPtrToLong = lngFnPtr End Function Sub PtrDemo() Dim l As Long, c As Byte, ca() As Byte, Pt As POINT Dim pl As Long, pc As Long, pv As Long, pPt As Long, pfnCompare As Long c = AscB("X") pl = VarPtr(l) '对应C里的long、int型指针 pc = VarPtr(c) '对应char、short型指针 pPt = VarPtr(Pt) '结构指针 pv = VarPtr(ca(0)) '字节数组指针,可对应任何类型,也就是void* pfnCompare = FnPtrToLong(AddressOf Compare) '函数指针 CopyMemory c, ByVal pc, LenB(c) '用指针取值 CopyMemory ByVal pc, AscB("Y"), LenB(c) '用指针赋值 pc = pc + LenB(c) : pl = pl - LenB(l) '指针移动 End Sub |
void *memcpy( void *dest, const void *src, size_t count ); |
欢迎光临 Office中国论坛/Access中国论坛 (http://www.office-cn.net/) | Powered by Discuz! X3.3 |