Re: Casting of bytes allocated by stackalloc to struct ptr -- It is possible but immediately

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"valentin tihomirov" <V_tihomirov@xxxxxxx> wrote in message news:uB3LRT3mHHA.668@xxxxxxxxxxxxxxxxxxxxxxx
Because the structure is extended by private fields. Why do you think the win api designers provide the functions to return output structure size for the user to allocate the buffer?

True, I didn't look at this particular struct in detail. Anyway in this case I would not use stackallock, stack alloc is great when you have to deal with small structs of blittable types.
I would rather use Marshal.AllocHGlobal to allocate the buffer and use Marshal.PtrToStruct() to marshal the buffer to a managed representation of the struct. This way I don't need to resort to unsafe code constructs, and I don't have to marshal the individual fields of the unmanaged buffer to their managed representation.
If you really want your unmanaged buffer to be stack allocated, you can always declare it like this:

... int jobs;
int bNeeded;
// Get buffer size needed
ret = EnumJobs(hPrinter, 0, 1, 2, IntPtr.Zero, bNeeded, out bNeeded, out jobs);
if(ret )
{
void* buffer = stackalloc byte[bNeeded];
EnumJobs(hPrinter, 0, 1, 2, ptr, bNeeded, out bNeeded, out jobs);
IntPtr ptr = new(buffer);
Marshal.PtrToStruct(ptr, ...);
..


Willy.



.



Relevant Pages