473,395 Members | 1,473 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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

Typically, you need the stackalloc when using win32 platform fucntions,
which tell you the amount of memory required for the output structure in the
first call, like GetJob does. The weired thing is that this works:
byte* p = stackalloc byte[size];
JOB_INFO_2* ji2 = (JOB_INFO_2*) p;

But the immediate casting does not:
JOB_INFO_2* ji2 = (JOB_INFO_2*) stackalloc byte[size];

It throws a lot of compilation messages. Peahaps, it is a compiler bug.
May 20 '07 #1
7 3665
"valentin tihomirov" <V_*********@best.eewrote in message
news:Oe*************@TK2MSFTNGP02.phx.gbl...
Typically, you need the stackalloc when using win32 platform fucntions,
which tell you the amount of memory required for the output structure in
the first call, like GetJob does. The weired thing is that this works:
byte* p = stackalloc byte[size];
JOB_INFO_2* ji2 = (JOB_INFO_2*) p;

But the immediate casting does not:
JOB_INFO_2* ji2 = (JOB_INFO_2*) stackalloc byte[size];

It throws a lot of compilation messages. Peahaps, it is a compiler bug.


Why not simply use?

JOB_INFO_2* ps = stackalloc JOB_INFO_2[1];

Willy.

May 20 '07 #2
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?
May 21 '07 #3
"valentin tihomirov" <V_*********@best.eewrote in message
news:uB*************@TK2MSFTNGP05.phx.gbl...
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.

May 21 '07 #4
Ok, I will tell you why marshalling is bad for p/invoking. Let me
demonstrate on the GetJob/SetJob example.

[1]

At first, DEVMODE is referred by pointer in JOB_INFO_2. But in .net, we
cannot use UnmanagedType.LPStruct:
[MarshalAs(UnmanagedType.LPStruct)] public DEVMODE pDevMode;

All the pointers to structures must be declared as opaque IntPtr. Thus, when
I unmarshal result of GetJob, the IntPtr devMode field will have some value
to be unmarshalled separately. After getting the print job settings, I
update the fields of interest and use SetJob to apply the updated settings
to the system. The SetJob invokation must be preceded by unmanaged space
allocation and marshalling. It will be done twice again (for job_info and
devmode). Furthermore, the IntPtr devMode field must be updated explicitly
accordingly.

As a conclustion, I have to do 22 lines of code, multiple heap memory
allocations and copy, where normally 2 lines of code with stack alloc and no
data copying suffices.
In addition to the code bloating, marshalling is not just possible in many
cases, since it requires exact structure descriptions. Take the
GetJob/SetJob example. I got the job settings into a structure, updated some
fields of it and wrote it back leaving other printing settings untouched.
The first two fields of DEVMODE are structure size and extra size. I do not
have the declarations of the extra fields. So Marshal.SizeOf(myDevMode) will
return a size smaller than specified in the size fields of the structure.
The spooler will fail on SetJob accessing the not described and thus not
allocated/marshaled fields.

Marshaling makes your code cumbersome and fragile.
May 21 '07 #5
"valentin tihomirov" <V_*********@best.eewrote in message
news:eu**************@TK2MSFTNGP06.phx.gbl...
Ok, I will tell you why marshalling is bad for p/invoking. Let me
demonstrate on the GetJob/SetJob example.

[1]

At first, DEVMODE is referred by pointer in JOB_INFO_2. But in .net, we
cannot use UnmanagedType.LPStruct:
[MarshalAs(UnmanagedType.LPStruct)] public DEVMODE pDevMode;

All the pointers to structures must be declared as opaque IntPtr. Thus,
when I unmarshal result of GetJob, the IntPtr devMode field will have some
value to be unmarshalled separately. After getting the print job settings,
I update the fields of interest and use SetJob to apply the updated
settings to the system. The SetJob invokation must be preceded by
unmanaged space allocation and marshalling. It will be done twice again
(for job_info and devmode). Furthermore, the IntPtr devMode field must be
updated explicitly accordingly.

As a conclustion, I have to do 22 lines of code, multiple heap memory
allocations and copy, where normally 2 lines of code with stack alloc and
no data copying suffices.
In addition to the code bloating, marshalling is not just possible in many
cases, since it requires exact structure descriptions. Take the
GetJob/SetJob example. I got the job settings into a structure, updated
some fields of it and wrote it back leaving other printing settings
untouched. The first two fields of DEVMODE are structure size and extra
size. I do not have the declarations of the extra fields. So
Marshal.SizeOf(myDevMode) will return a size smaller than specified in the
size fields of the structure. The spooler will fail on SetJob accessing
the not described and thus not allocated/marshaled fields.

Marshaling makes your code cumbersome and fragile.

All depends on the usage scenario, on what structure you have to deal with,
what fields you need to use in your code in managed form, for instance if
you need to get at the items declared as LPTSTR you'll have to marshal these
to a System.String anyway.
I agree that in your scenario, where you only need the raw structure to
modify some fields and pass this back to another API, you can go without
marshaling, however, I don't like unsafe constructs.
I agree, that some Win32 structs are hard to marshal, this is where C style
data types meets OO style (and this is also a reason why some Win32 API's
are not wrapped in the FCL), dealing with API's designed for "C " from other
languages is by itself cumbersome and fragile.
That's why I wouldn't use C# to access the spooler API's, I would use
C++/CLI. This is also what MS is doing, some of the new FCL classes are now
written using managed C++, it's easier to get it right, especially when you
have to deal with a lot of (OS version dependent) API's and structures, much
is taken care of in the header files. I wonder how much of the FCL would
have been written using C# if C++/CLI had been available since day one?

Willy.
Willy.

May 21 '07 #6
"valentin tihomirov" <V_*********@best.eeschrieb im Newsbeitrag
news:Oe*************@TK2MSFTNGP02.phx.gbl...
Typically, you need the stackalloc when using win32 platform fucntions,
which tell you the amount of memory required for the output structure in
the first call, like GetJob does. The weired thing is that this works:
byte* p = stackalloc byte[size];
JOB_INFO_2* ji2 = (JOB_INFO_2*) p;

But the immediate casting does not:
JOB_INFO_2* ji2 = (JOB_INFO_2*) stackalloc byte[size];

It throws a lot of compilation messages. Peahaps, it is a compiler bug.
Following the specification of C# the stackalloc construct can only be used
as variable initializer. Maybe its only meant for declaring 'unsafe
variables'.

Christof
May 22 '07 #7
"Christof Nordiek" <cn@nospam.dewrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
"valentin tihomirov" <V_*********@best.eeschrieb im Newsbeitrag
news:Oe*************@TK2MSFTNGP02.phx.gbl...
>Typically, you need the stackalloc when using win32 platform fucntions,
which tell you the amount of memory required for the output structure in
the first call, like GetJob does. The weired thing is that this works:
byte* p = stackalloc byte[size];
JOB_INFO_2* ji2 = (JOB_INFO_2*) p;

But the immediate casting does not:
JOB_INFO_2* ji2 = (JOB_INFO_2*) stackalloc byte[size];

It throws a lot of compilation messages. Peahaps, it is a compiler bug.

Following the specification of C# the stackalloc construct can only be
used as variable initializer. Maybe its only meant for declaring 'unsafe
variables'.

Christof
This is not the point, JOB_INFO_2* is an unsafe variable (it's a pointer
variable).
JOB_INFO_2* ptr = stackalloc JOB_INFO_2[2]
compiles just fine, the point is that the compiler doesn't like the cast in:
JOB_INFO_2* ptr = (JOB_INFO_2*)stackalloc byte[sizeofjob_info_2];
I don't know if it's a bug, looks more like a missing feature. Anyway not
quite a big issue, the bypass is illustrated by the OP.

Willy.

May 22 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A...
5
by: Alex Vinokur | last post by:
"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c > ben19777@hotmail.com (Ben) wrote: > > 2) Structure casted into an...
19
by: becte | last post by:
I need to use three bytes to store four 6-bit integers (4 * 6 = 3 * 8) like this 11111122|22223333|33444444 Suppose the input is, int c1, c2, c3, c4, range 0 .. 2^6 -1 and the output is int...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
20
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct...
6
by: Daniel O'Connell | last post by:
Two questions here: 1. Is there any particular reason why when using stackalloc, the code byte *buffer = stackalloc byte; works, but code like byte *buffer; buffer = stackalloc byte; is...
12
by: Olaf Baeyens | last post by:
I am porting some of my buffer class code for C++ to C#. This C++ class allocates a block of memory using m_pBuffer=new BYTE; But since the class is also used for pointers for funtions that uses...
3
by: LongBow | last post by:
Hello all, First of all, sorry for multiple question per one thread. I have two questions. First what I think might be the easier problem. I am capturing data from an embedded device which I...
11
by: redefined.horizons | last post by:
First, I would thank all of those that took the time to answer my question about creating an array based on a numeric value stored in a variable. I realize after reading the responses and doing...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.