VB really cannot think of the second series: VB "sunflower Collection"-pointer Technology

Source: Internet
Author: User
Tags knowledge base

VB is an unexpected Series
Every time I see the wonderful things of the master, I will scream: "Wow, I can't think of it! ". After many such feelings, I found that as long as we use our brains, we can make things unexpected to others. So I want to share these unexpected things with you, hoping to attract more unexpected things.

VB really cannot think of the second series: VB "sunflower Collection"-pointer Technology
Keywords: VB, pointer, dynamic memory allocation, efficiency, security
Difficulty: intermediate to advanced
Requirements: Be familiar with VB, master basic C, understand assembly, and understand the principle of memory allocation.
Think that the East is undefeated, black Cliff secret room battle, only with a embroidery needle fight four Masters alone, no ghost, called the world's first martial arts. If you want to become an undefeated player in VB, You can familiarize yourself with VB's "sunflower Collection" and master the VB pointer technology.
If you want to exercise the power of your work ......, In fact, it is not so painful to master the VB pointer technology. When I talk about it, I have just a few tricks and I will work hard to practice it. Let's start with the definition of pointers.

I. What is a pointer?
There is no need to look for a standard definition. It is a 32-bit integer, which can be expressed in C and VB using the long type. On a 32-bit Windows platform, it is no different from a common 32-bit long integer, except that its value is a memory address because the integer points to a memory address like a needle, so we have the pointer concept.
Statistics show that a large part of program defects are related to incorrect memory access. Because pointers directly deal with memory, pointers have always been seen as dangerous. So many languages, such as the famous java, do not support pointer operations. All memory access processing is done by the compiler. Like C and C ++, pointers are basic skills. Pointers give programmers great freedom to handle memory access as they wish, many clever things rely on Pointer technology.
I will not discuss whether pointer operations should be canceled for an advanced programming language, the lack of results on the Internet has led to the use of several GB of resources. Whether or not you have to make up your mind to learn the pointer technology "sunflower Collection", it is always helpful to understand this effort.
Note: In VB, the official website does not encourage the use of pointer. you do not expect to obtain official technical support for anything mentioned in this Article. Everything depends on our own efforts, everything is even more exciting!
Let's start a magical VB pointer adventure!

2. Let's see what the pointer can do? What is the purpose?
Let's look at two programs. The functions of the program are to exchange two strings:
[Procedure 1]: 'standard practice swapstr
Sub swapstr (SA as string, Sb as string)
Dim stmp as string
Stmp = sa: SA = SB: SB = stmp
End sub

[Procedure 2]: 'swapptr with pointers
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

Do you think that the first program is faster, because it looks simple and does not need to call the API (calling the API requires additional processing, VB clearly states that a large number of API calls will reduce program performance ). But in fact, in the VB integrated environment, Program 2 is 1/4 faster than the program; while the compilation cost machine code or p-code is basically twice faster than the program. The following is a comparison of the time taken to run the two functions after being compiled into the local code:
It takes 100000 milliseconds to run swapstr 170 times and 90 milliseconds to run swapptr.
It takes 200000 milliseconds to run swapstr 340 times and 170 milliseconds to run swapptr.
It takes 2000000 milliseconds to run swapstr 3300 times and 1500 milliseconds to run swapptr.
Indeed, calling an API requires additional instructions. However, because pointer technology is used, it does not allocate or copy temporary strings. Therefore, the speed has improved a lot.
How can this problem be solved! C/C ++ programmers rely on pointers so much that they can use pointers to handle the root cause of the problem more directly and control the pleasure of everything. They do not know the danger of using pointers. They are not unwilling to drive a satellite to locate a variable-speed car, but riding a motorcycle is more pleasant. In some places, only motorcycles can pass.
Like in C, we can use pointers in VB for only three reasons:
First, efficiency is a kind of attitude and pursuit, which is the same in VB;
Second, it cannot be used because the operating system is written in C, and it always reminds us that it needs pointers;
The third is to break through the restrictions. VB wants to take care of everything. VB gives us a strong type check. Like our mom, VB cares about us and sometimes we can't stand it, do you want to listen to mom occasionally? You need a pointer!
However, in VB, pointers become mysterious due to lack of official technical support. Therefore, some basic technologies in C become more difficult in VB. The purpose of this article is to provide you with a simple method to get the C processing pointer technology to VB and tell you what is feasible, you must be careful about what is feasible, what is possible but not feasible, and what is impossible at all.

Iii. Three Axes of Cheng Zhijin
Yes, Program 2 basically shows the appearance of the VB pointer technology. To sum up, we need to master three things using pointer Technology in VB: copymemory, varptr/strptr/objptr, and adressof. three axes, the three axes of Cheng Zhijin, And the hack tool in VB.
1. copymemory
For the legends of copymemory and Bruce McKinney, there is an article in the knowledge base of msdn. You can search for the article "ID: q129947. It was the master who brought this mobile memory API to the 32-bit VB. With this API, we can use pointers to do the work we did not dare to think about, thanks to Bruce McKinney for bringing us the pointer revolution of VB.
For example, the copymemory statement defines the rtlmovememory API in kernel32.dll. memcpy in the 32-bit C-function library is the packaging of this API, as mentioned in the msdn document, its function is to copy the memory with a length starting from the source pointer to the memory indicated by destination. It does not care whether our program has the permission to read and write the memory. when it wants to read and write the memory protected by the system, we will get the famous access violation fault (memory unauthorized access error), and even cause the more famous general protection (GP) fault (general protection error ). Therefore, when conducting experiments in this series of articles, be sure to save your program files at any time, in the VB integration environment, set "Startup Program" in the "Environment" tab of "Tools"-> "options" to "save changes ", remember to save our work results before executing dangerous code in the "immediately" window.

2. vatptr/strptr/objptr
They are good treasures provided by VB. They are hidden functions in the VBA function library. Why hide it? We are not encouraged to use pointers because of the VB development team.
In fact, these three functions are the same function varptr In the VB Runtime Library msvbvm60.dll (or msvbvm50.dll) (see the method I introduced in the first article in this series ).
Its Library is defined as follows:
[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 );
Even though they are the same function in the VB Runtime Library, we can re-declare these functions using APIs in VB, as shown below:
Private declare function objptr lib "msvbvm60" alias "varptr "_
(VaR as object) as long
Private declare function varptr lib "msvbvm60 "_
(VaR as any) as long
(Without strptr, it is because VB has different processing methods for strings, and there are too many problems in this regard. In this series, I will use another article "VB string Raiders" for details.
By the way, I heard that VB. net does not have these functions, but as long as the API can be called, we can try the above several declarations, so in VB.. net.
However, note that if varptr is called through the API, the whole program's second swapptr will be 6 times slower than the original built-in varptr function .)
If you like to answer questions, the following is how varptr functions look in C and assembly languages:
In C, it looks like this:
Long varptr (void * PV ){
Return (long) PV;
}
The correct assembly code has two lines:
MoV eax, dword ptr [esp + 4]
RET 4' the parameter values in the stack are displayed and returned.
To let everyone know the specific implementation of varptr, I want to tell you that it is not costly, because they only have two commands, even if you add parameter values, pressure stacks, and call commands, the entire process of getting a pointer is six commands. Of course, the same function is in the C language. Because of the direct support of the language, only one instruction is required. But in VB, it is already the fastest function, so we do not have to worry about using varptr will make us lose efficiency! Speed is the fundamental requirement for using pointer technology.
In a word, varptr returns the memory address where the variable is located. It can also be said that it returns a pointer to the memory location of the variable. It is one of the most important weapons for us to process pointers in VB.

3. byval and byref
The parameter value passed by byval, and the address of the parameter passed by byref. Here, we do not need to distinguish between passing pointer, passing address, and transferring reference. In VB, they are three different statements of one thing, even in VB documents, these terms are mixed (but pointers and references must be distinguished in C ++)
If you are new to swapptr, you must find out where to add byval to the copymemory call, where is not added (if byval is not added, the default byref of VB is used)
An accurate understanding of the difference between passing a value and passing an address (pointer) is the basis for correct pointer usage in VB.
Now, let's look at this problem through a simple experiment. The procedure is as follows:
[Procedure 3]: 'Experience byval and byref
Sub testcopymemory ()
Dim K as long
K = 5
Note: copymemory byval varptr (K), 40000, 4
Debug. Print K
End sub
The purpose of the statement at the preceding note is to assign K to 40000, which is equivalent to statement K = 40000. You can test it in the "now" window, we will find that the value of K is indeed 40000.
In fact, the above statement is translated into vernacular, that is, four bytes are copied from the temporary variable storing constant 40000 to the memory where variable k is located.
Now let's change the statement at a note. If it is changed to the following statement:
Note2: copymemory byval varptr (K), byval 40000, 4
The meaning of this statement is: Copy 4 bytes from address 40000 to the memory where the variable k is located. Because we do not have permission to access the memory where address 40000 is located, the operating system will give us an access violation memory unauthorized access error, telling us "An error occurred while trying to read the memory at location 0x00009c40, the memory cannot be 'read '".
Let's change it to the following statement.
Note3: copymemory varptr (K), 40000, 4
The meaning of this statement is that four bytes are copied from the temporary variable that saves constant 40000 to the temporary variable that saves the memory address value of variable k. This will not cause an out-of-memory unauthorized access error, but the value of K has not changed.
We can change the program to clear the difference, as shown in the following procedure 4:
[Program 4]: 'Let's see where our stuff has been copied.
Sub testcopymemory ()
Dim I as long, K as long
K = 5
I = varptr (k)
Note 4: copymemory I, 40000, 4
Debug. Print K
Debug. Print I
I = varptr (k)
Note5: copymemory byval I, 40000, 4
Debug. Print K
End sub

Program output:
5
40000
40000
Because the default byval is used in note4, the address of I is passed (that is, the pointer to I), so constant 40000 is copied to variable I, so the value of I is 40000, the value of K remains unchanged. However, before note4: I = varptr (k), the intention is to use I as a pointer. In this case, we must use byval as note5 to pass the pointer I. Since I is a pointer to the variable k, the constant 40000 is copied to the variable k.
I hope you have understood this difference. I will discuss it later.

4. addressof
It is used to obtain a pointer to the VB Function entry address, but this pointer can only be passed to the API for use, so that the API can call back the VB Function.
Function pointers are not discussed in detail in this article. For more information about how to use them, see the VB document.

5. tailism.
In fact, with the copymemory, varptr, and addressof axes, we can take the basic pointer operations in C.
The following C program includes most basic pointer operations:
Struct point {
Int X; int y;
};
Int compare (void * elem1, void * elem2 ){}
Void ptrdemo (){
// Pointer declaration:
Char c = 'X'; // declare a char variable
Char * PC; long * pl; // declare normal pointer
Point * PPT; // declare the structure pointer
Void * PV; // declare No type pointer
INT (* pfncasttoint) (void *, void *); // declare the function pointer:
// Pointer assignment:
PC = & C; // assign the address value of variable C to the pointer PC
Pfncompare = compare; // function pointer assignment.
// Pointer value:
C = * PC; // assign the memory value specified by the pointer PC to variable C
// Assign values using pointers:
* Pc = 'y' // assign 'y' to the memory variable specified by the pointer PC.
// Pointer movement:
PC ++; pl --;
}

These pointer operations are equivalent in VB,
The previous discussions about byval and byref mentioned that pointer passing and address passing are the same thing. In fact, when we use the default byref in VB to declare function parameters, we have already declared pointers.
For example, a function declared by C: Long func (char * PC)
The corresponding VB declaration is: function func (PC as byte) as long
In this case, the parameter PC uses the default byref address transfer method to pass the parameter, which is the same as using a pointer in C to pass the parameter.
So how can we declare a pointer as clearly as in C?
As mentioned above, a 32-bit long integer can be used to express the pointer. In VB, the long type is used to explicitly declare pointers. We do not need to distinguish between common pointers, non-type pointers, or function pointers. Long can be used to declare pointers. Assign a pointer to the address of another variable obtained by varpar. For details, see program 5.
[Procedure 5]: various pointers, like C.
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) 'corresponds to long and INT pointers in C.
PC = varptr (c) 'corresponds to Char and short pointers
PPT = varptr (PT) 'structure pointer
Pv = varptr (CA (0) 'byte array pointer, which can correspond to any type, that is, void *
Pfncompare = fnptrtolong (addressof compare) 'function pointer
Copymemory C, byval PC, lenb (c) 'with pointer Value
Copymemory byval PC, ASCB ("Y"), lenb (c) 'is assigned with a pointer
PC = PC + lenb (c): PL = pl-lenb (l) 'pointer Movement
End sub
We can see that because VB does not directly support pointer operations, the copymemory API must be used for pointer values and pointer values in VB, And the API call cost is relatively high, this determines that we cannot use pointers as frequently and freely as in C in VB. We must consider the cost of pointer operations, in the "pointer application", we will discuss this issue again.
For more information about function pointers in program 5, see the VB document. The void of the non-type pointer * will be described in the "questions about any" section below.
Program 5 basically includes all pointer operations that we can perform in VB.

The following is a small test question. If you understand the three axes of Cheng Zhijin, you should be able to do it.
As mentioned above, there is no varptr in VB. NET. We can introduce varptr in msvbvm60.dll by declaring the API. If you do not need the DLL file at runtime of VB, can you implement an objptr by yourself. The answer is given in the next section.

Iv. Precautions for pointer usage
1. Questions about any
If I speak as a teacher, I will say: I 'd better never use any! Yes, I'm not wrong. It's always! So I didn't put it in the three axes of Cheng Zhijin. Of course, this question is the same as whether to use pointers. It will lead to a discussion without any results. I only tell you a point of view, sometimes we use any to improve efficiency or to get a little lazy, but this requires taking risks.
Any is not a real type. It just tells the VB compiler to discard the parameter type check. In this way, theoretically, we can pass any type to the API.
Where is any used? Let's take a look at what is said in the VB document. Now open msdn (the version that comes with Visual Studio 6 ), go to the "Visual Basic documentation"-> "Use Visual Basic"-> "part Tool Guide"-> "Access DLL and Windows API" section, let's take a look at the section "converting the C language declaration to the Visual Basic Declaration. The document tells us that we only use any when C is declared as lpvoid and null. In fact, if you are willing to take risks, you can use any for all types. Of course, as I said, never use any.
Why? Why does VB officially provide any? Do you trust me or the official VB team? Why not use any?
As mentioned above, VB does not encourage us to use pointers. One of the advantages advertised by VB is that there are no dangerous pointer operations, so the memory access is controlled by the VB Runtime Library. At this point, the Java language is also advertised. However, like Java, to avoid using pointers for higher security, VB must overcome the problems caused by no pointers. VB has done its best to keep us away from pointers while having the Security brought by strong type checks. However, the operating system is written in C, and pointers are needed everywhere. some pointers are of no type, that is, the terrible void * That C programmers often say has no type pointer. It has no type, so it can represent all types. For example, copymemory corresponds to memcpy in C language, and its declaration is as follows:
Void * memcpy (void * DEST, const void * SRC, size_t count );
Because the first two parameters of memcpy use void *, any type of parameters can be passed to him.
A programmer using C should know that such void * in the C function library is not uncommon, but also how dangerous it is. No matter what type of variable pointer is passed to the void * of memcpy above, the C compiler will not report an error or give any warning.
In VB most of the time, we use any to use void *. Like in C, VB does not perform any type check. We can also pass any type to any, the VB compiler does not report errors or give any warning.
But whether the program runs correctly depends on whether you are careful when using it. Because many errors in C are related to void *, C ++ encourages us to use satic_cast <void *> to explicitly point out this unsafe type conversion, it is conducive to error discovery.
After talking about so many C/C ++, I want to tell all VB programmers that when using any, we must be as careful as C/C ++ programmers when using void.
There is no such thing as satic_cast in VB, but we can use the long type explicitly when passing the pointer and use varptr to obtain the parameter pointer, this at least clearly indicates that we are using dangerous pointers. For example, after such processing, Program 2 becomes the following program:
[Procedure 5]: 'Use a safer copymemory and use a pointer explicitly!
Private declare sub copymemory lib "Kernel32" alias "rtlmovememory" (byval destination as long, byval source as long, byval length as long)
Sub swapstrptr2 (SA as string, Sb as string)
Dim ltmp as long
Dim pTMP as long, PSA as long, PSB as long
PTMP = varptr (ltmp): PSA = varptr (SA): PSB = varptr (SB)
Copymemory pTMP, PSA, 4
Copymemory PSA, PSB, 4
Copymemory PSB, pTMP, 4
End sub
Note that the above copymemory statement uses byval and long, and requires that the 32-bit address value be passed. When we pass another type to this API, the compiler reports an error, for example, the following statement is used:
Program 6: A bit like program 4, but the constant 40000 is replaced with a variable with a value of 1.
Private declare sub copymemory lib "Kernel32" alias "rtlmovememory" (byval destination as long, byval source as long, length as long)
Sub testcopymemory ()
Dim I as long, K as long, Z as interger
K = 5: z = 1
I = varptr (k)
'The following statements may cause compilation errors of different types. This is a good thing!
'Copymemory I, Z, 4
'Use the following
Copymemory I, byval varptr (z), 2
Debug. Print K
End sub
Compilation will fail! It's a good thing! This is better than running without knowing where the error is!
Similar to program 4, if the any type is used to declare the copymemory parameter, VB does not report an error, but the running result is incorrect. Believe it or not, change 40000 in program 4 to 1. The result I is 327681 instead of 1. In program 4, if the constant is set to 1, the result is incorrect. If the constant is set to 40000, the result is good?
The reason is that VB processes constants in function parameters in variant mode. When the value is 1, because 1 is less than 32767 of the integer type's maximum value, VB will generate a temporary variable of the integer type storing the value 1, that is, when we want to copy 1 from copymemroy to long variable I, this constant 1 is actually an integer Temporary Variable! In VB, the integer type has only two bytes, and we actually copied four bytes. You know how dangerous it is! We are lucky to have no memory protection error!
If you must explain why I finally changed to 327681, this is because we copied the low 16-bit K value 5 to the high 16-bit I value, therefore, 5*65536 + 1 = 327681. This issue involves the Declaration sequence of VB local variables, the pressure stack sequence of the copymemory parameter, and the low position of the long type. If you are interested in these issues, you can use the methods provided in the first article in this series (debugbreak API and VC debugger) to trace them, it can deepen your understanding of the internal processing methods of VB. This has nothing to do with the problems discussed in this article, so we will not discuss them in detail. At this point, we should understand that there are actually errors in program 3 and program 4 !!! I used the constant 40000 instead of 1 above, not to gather words in the article, but because the constant 40000 is greater than 32767, it will be interpreted by VB as a temporary variable of the long type we need, only in this way can program 3 and program 4 work normally. Sorry, I only wish to deepen your understanding of the dangers of any.
In short, we need to realize that it is very important to find errors during compilation, because you will immediately know where the errors are. So we should use the byval pointer of the long type as program 5 and program 6, rather than the byref pointer of any.
However, the use of any has become so popular that many masters have used it. Its unique charm is that, unlike the long pointer, we need to call varptr ourselves to get the pointer. All the processing of the pointer is done by the VB compiler. Therefore, in parameter processing, only one assembly command is used: Push [I]. When varptr is used, five Assembly commands must be used because a function call is required. Five redundant Assembly commands sometimes let us use any at risk.
If the VB development team provides any, it wants to use byref XXX as any to express void * XXX. We can also use varptr and long pointers for processing. I think, the VB development team also hesitated to publish varptr or provide any. Finally, they decided to provide any and continue to conceal varptr. Indeed, this is a dilemma. However, after my analysis above, we should know that this decision is not in line with the original intention of "more secure" pursued by VB. Because it may hide errors of different types, debugging and identifying errors generated during the running process will take more time and effort.
So I have come to the conclusion that "never use any" is amazing.

Another advantage of not using any is that it simplifies the way we convert the C-declared API into a VB declaration. Now it becomes a sentence: apart from the built-in type of VB that can perform type checks, therefore, we should declare other types as long.

2. obfuscation of null
Many articles have been mentioned, so be sure to keep them in mind:
Vbnullchar is equivalent to '/0' in C. It is often used as the last element to construct a C string using a byte array.
Vbnullstring this is the true null, that is, 0. You can use 0 directly in VB6.
Only the two above are used in API calls. Empty and null are variant, while nothing is only related to class objects, which are not used in API calls.

In section 3 of this article, I have proposed a small test question. Have you made it? The correct answer is now published:
[Test answer]
Function objptr (OBJ as object) as long
Dim lpobj as long
Copymemory lpobj, OBJ, 4
Objectptr = lpobj
End Function

V. VB pointer Application
As mentioned above, using pointers in VB is not as flexible as in C. When using pointers to process data, you need to use copymemory to copy the data back and forth between the variables that can be processed by pointers and VB, this requires a large amount of extra cost. Therefore, not all pointer operations in C can be moved to VB. We should only use pointers in VB when necessary.
1. Dynamic Memory Allocation: completely impossible, possible, but not feasible. VB Standard
One important reason for frequent pointer usage in C and C ++ is the need to use dynamic memory allocation and use malloc or new to dynamically allocate memory from the stack, and get the pointer pointing to this memory. In VB, we can also
You can use APIs to dynamically allocate memory and implement linked lists like pointers in C.
However, we cannot directly use pointers to access such dynamically allocated memory as C. During access, we must use copymemory to copy the data to the VB variable, A large amount of use of this technology will inevitably reduce efficiency, so it is impossible to use dynamic memory with pointers like C. To implement a dynamic data structure like C and Pascal, we should still implement it with honest and practical object technology in VB.
The inventory list in the code in this article contains a linked list fully implemented by pointers. It uses heapalloc to dynamically allocate memory from the stack, another small program that calls the findfirsturlcacheentry API to operate ie cache iecache uses virtualalloc to dynamically allocate memory. But in fact this is not necessary. VB has provided us with a standard dynamic memory allocation method, that is:
Object, string, and byte array
For more information about object technology, refer to the linked list implemented by objects in the source code of the listing list.
Strings can be dynamically allocated using the space $ function. Detailed descriptions are provided in the VB document.
The byte array is very useful. We can use redim to dynamically change its size, and pass the pointer pointing to its first element to the API that needs the pointer, as shown below:
Dim AB () as byte, RET as long
'The API that passes the null value will return the length of the buffer required by the API.
Ret = someapineedsbuffer (vbnullstring)
'Dynamically allocate enough memory buffers
Redim AB (RET) as byte
'Send the pointer to the API again, and then pass the pointer of the first element of the byte array.
Someapineedsbuffer (byval varptr (AB (1 )))
In iecache of the supporting program in this article, I also provide a version that uses byte Arrays for Dynamic Buffer Allocation, Which is safer and easier than virtualalloc.

2. Breakthrough
The following is a classic application that breaks through the VB type check to implement special functions, from Bruce McKinney's book hardcore Visual Basic.
Extract the low 16 bits of a long integer as the interger type,
[Procedure 7] 'The standard method is also an efficient method, but it is not easy to understand.
Function loword (byval DW as long) as integer
If DW and & h8000 & then
Loword = DW or & hffff0000
Else
Loword = DW and & hffff &
End if
End Function
[Procedure 8] 'The efficiency of using pointers is not high, but the idea is clear.
Function loword (byval DW as long) as integer
Copymemory byval varptr (loword), byval varptr (DW), 2
End Function

3. batch operation on Arrays
It is necessary to use pointers to move a large volume of array data in terms of efficiency. Looking at the two programs below, their functions are to move the first half of the array data to the next half:
[Procedure 9]: 'The standard method of moving an array
Private sub shitarray (AB () as mytype)
Dim I as long, N as long
N = clng (ubound (AB)/2)
For I = 1 to n
Value (n + I) = value (I)
Value (I). Data = 0
Next
End sub
[Procedure 10]: 'Use pointers
Private declare sub copymemory lib "Kernel32" alias "rtlmovememory "_
(Byval DEST as long, byval source as long, byval bytes as long)
Private declare sub zeromemory lib "Kernel32" alias "rtlzeromemory "_
(Byval DEST as long, byval numbytes as long)
Private declare sub fillmemory lib "Kernel32" alias "rtlfillmemory "_
(Byval DEST as long, byval length as long, byval fill as byte)

Private sub shitarraybyptr (AB () as mytpye)
Dim N as long
N = clng (ubound (AB)/2)
Dim nlenth as long
Nlenth = Len (value (1 ))
'Destbugbreak
Copymemory byval varptr (value (1 + n )),_
Byval varptr (value (1), N * nlenth
Zeromemory byval varptr (value (1), N * nlenth
End sub
When the array is large and there are many mobile operations (for example, hashtable using arrays), program 10 is much better than program 9.
Program 10 introduces two APIs used in Pointer operations: zeromemory is used to clear the memory; fillmemory is used to fill the memory in the same byte. Of course, the functions of these two APIs can also be completed using copymemory. Like in C, as a good habit, in VB, we can also explicitly use zeromemory to initialize the array, and use fillmemory to fill in a strange value in memory that is not used immediately, this facilitates debugging.
4. Last point
Of course, the application of the VB pointer never stops this. It is up to you to explore any other application. I will write an article on the application of object pointers and string pointers as the end of this article and the start of the next article "VB string Raiders, here is the fastest way to exchange two strings:
[Program 11] 'The fastest way to swap two strings
Private declare sub copymemory lib "Kernel32" alias "rtlmovememory" _ (destination as any, source as any, byval length as long)

Sub swapstrptr3 (SA as string, Sb as string)
Dim ltmp as long
Dim pTMP as long, PSA as long, PSB as long
PTMP = strptr (SA): PSA = varptr (SA): PSB = varptr (SB)
Copymemory byval PSA, byval PSB, 4
Copymemory byval PSB, pTMP, 4
End sub
Sorry, I used any again for a little efficiency! I will talk about strptr in the next article.
Try it by yourself! To learn how to work, hurry up!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.