Is Pointer Casting To Satisfy Method Params A Dangerous Thing To Do?
This might be rather simple but I have a method that expects a parameter to be of type BYTE **Ptr
And for various reasons I am using an int* (we'll call intPtr
for this example) in the code that will call this method, so I was wondering if it is safe to do this:
MethodCall((BYTE**) &intPtr, ...
The method locks an image buffer in place and you supply a BYTE* to it so that once it has locked the buffer it sets the pointer to point to the start of the locked buffer in memory. This is part of the Windows Media Foundation code and so cannot be easily changed to suit my int*.
Will the casting above do the job of having my intPtr
still point to the locked buffer memory address after the call, as if it were a BYTE* as requested. Also, is there any d开发者_运维知识库anger to doing this?
In general, this is not "safe". Whilst a pointer-to-T
may be converted to a pointer-to-U
and back again, modifying it via the pointer-to-U
is, at best, implementation-defined.
In your example, the method will modify your int *
to point at some memory, but there's no guarantee that that it will choose some memory that is correctly aligned for int
. This would lead to what's known as "a big mess".
Practically, on Windows, this is probably going to work, since BYTE*
and int*
have the same size. In general though this is undefined behaviour, and there's no reason why pointers of different types should be of the same size -- the only pointer that's guaranteed to fit any other pointer is void*
.
Yes, it's dangerous thing if you aren't downcasting class pointer. It may crop in that case int value.
And in that case BYTE**
is pointer to pointer or array of pointers, so casting it from int is dangerous and function may corrupt the other part of memory.
精彩评论