关于LPVOID的一点问题

来源:互联网 发布:windows 位置不可用 编辑:程序博客网 时间:2024/05/16 09:00

LPVOID是一个没有类型的指针,也就是说你可以将任意类型的指针赋值给LPVOID类型的变量(一般作为参数传递),然后在使用的时候再转换回来。

LPVOID 和CString 的转换

CString str("123");

LPSTR lpstr=str.GetBuffer();//这个不能用于Unicode(LPWSTR)

LPVOID lpvoid=(LPVOID)lpstr;

str.ReleaseBuffer();

思路:

先取得指向CString对象里的内容的指针 LPSTR lpstr = str.GetBuffer();

然后将这个指针转换成LPVOID类型(强制类型转换)


一个相关的解释:

There is no LPVOID type in C, it's a Windows thing.
And the reason those sort of things exists is so that the underlying types can change from release to release without affecting your source code.
For example, let's say early versions of Microsoft's C compiler had a 16-bit int and a 32-bit long. They could simply use:
typedef long INT32 and, voila, you have your 32-bit integer type.
Now let's go forward a few years to a time where Microsoft C uses a 32-bit int and a 64-bit long. In orfer to still have your source code function correctly, they simply change the typedef line to read:
typedef int INT32 This is in contrast to what you'd have to do if you were using long for your 32-bit integer types. You'd have to go through all your source code and ensure that you changed your own definitions.
It's much cleaner from a compatibility viewpoint (compatibility between different versions of Windows) to use Microsoft's data types.
In answer to your specific question, it's probably okay to void* instead of LPVOID provided the definition of LPVOID is not expected to change.
But I wouldn't, just in case. You never know if Microsoft may introduce some different way of handling generic pointers in future that would change the definition of LPVOID. You don't really lose anything by using Microsoft's type but you could be required to do some work in future if they change the definition and you've decided to use the underlying type.
You may not think pointers would be immune to this sort of change but, in the original 8088 days when Windows was created, there were all sorts of weirdness with pointers and memory models (tiny, small, large, huge et al) which allowed pointers to be of varying sizes even within the same environment.


原创粉丝点击