473,545 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Extra byte in type classes?

115 New Member
I'm looking for a better understanding of whats going on with the code i write. I have come across something that I thought I understood but its not working as expected. Its hard to explain so let me show the code first..

Expand|Select|Wrap|Line Numbers
  1.         [DllImport("activeds.dll", EntryPoint = "ADsOpenObject", CharSet = CharSet.Unicode, ExactSpelling = true)]
  2.         private static extern int IntADsOpenObject(string path, string userName, string password, int flags,ref MyGuid iid, [MarshalAs(UnmanagedType.Interface)] out object ppObject);
  3.  
  4.         struct MyGuid
  5.         {
  6.             public Int32 Data1;
  7.             public Int16 Data2;
  8.             public Int16 Data3;
  9.  
  10.             public Byte Data4_1;
  11.  
  12.             public Byte Data4_2;
  13.             public Byte Data4_3;            
  14.             public Byte Data4_4;
  15.             public Byte Data4_5;            
  16.             public Byte Data4_6;
  17.             public Byte Data4_7;
  18.  
  19.             public Byte Data4_8;
  20.         }
  21.  
  22.         static void Main(string[] args)
  23.         {
  24.             //Guid l = new Guid("00000000-0000-0000-C000-000000000046");
  25.  
  26.             object obj = null;
  27.             MyGuid g = new MyGuid();
  28.  
  29.             g.Data4_1 = 192;
  30.             g.Data4_8 = 70;
  31.  
  32.             int j = IntADsOpenObject("LDAP://thedomain.com", "username", "password", 1, ref g, out obj);
  33.             Console.WriteLine(j.ToString());
  34.         }
This works as expected..(save replacing the strings with valid domain, username and password)

When I try to replace the last two bytes in the structure with a short datatype it no longer works..i.e:

Expand|Select|Wrap|Line Numbers
  1.         [DllImport("activeds.dll", EntryPoint = "ADsOpenObject", CharSet = CharSet.Unicode, ExactSpelling = true)]
  2.         private static extern int IntADsOpenObject(string path, string userName, string password, int flags,ref MyGuid iid, [MarshalAs(UnmanagedType.Interface)] out object ppObject);
  3.  
  4.         struct MyGuid
  5.         {
  6.             public Int32 Data1;
  7.             public Int16 Data2;
  8.             public Int16 Data3;
  9.             public Byte Data4_1;
  10.  
  11.             public Byte Data4_2;
  12.             public Byte Data4_3;            
  13.             public Byte Data4_4;
  14.             public Byte Data4_5;            
  15.             public Byte Data4_6;
  16.  
  17.             public Int16 Data4_7_8;//Same number of bytes?
  18.             //public Byte Data4_7;
  19.             //public Byte Data4_8;
  20.         }
  21.  
  22.         static void Main(string[] args)
  23.         {
  24.             //Guid l = new Guid("00000000-0000-0000-C000-000000000046");
  25.  
  26.             object obj = null;
  27.             MyGuid g = new MyGuid();
  28.  
  29.             g.Data4_1 = 192;
  30.             g.Data4_7_8 = 70;
  31.  
  32.             int j = IntADsOpenObject("LDAP://thedomain.com", "username", "password", 1, ref g, out obj);
  33.             //No longer works
  34.  
  35.             Console.WriteLine(j.ToString());
  36.         }
Am i misunderstandin g something? The Int16 class is a short datatype which is only two bytes (I thought)..so replacing the two bytes with the short should be exactly the same. What is breaking this?

(Yes I know i could just pass the Guid type in and it would work but im looking to understand the code to stop just grabing solutions off the net.)
Nov 25 '08 #1
10 2872
Plater
7,872 Recognized Expert Expert
Well I don't really know the "why" either, but I had figured it would not work. Managed Structs don't work the way unmanged (c++) structs worked. Where the bytes were just folded on top of the struct and "filled it in"
I think if you maybe fiddle with the [StructLayout] and packing stuff you can make it work
Nov 25 '08 #2
mldisibio
190 Recognized Expert New Member
Not completely sure either, but Byte is unsigned and Int16 is signed, so the leftmost of the 16 bits is reserved for the sign, meaning it is not truly two 8 bit values. [1000 0000 0000 0000 = -32768 not +32768] and the MaxValue is [0111 1111 1111 1111 : 0x7FFF not 0xFFFF]

That said, I cannot explain why the decimal 70 would make any difference.

Nonetheless, theoretically it might work if you used UInt16, unsigned, but that is not CLR compliant and so I wonder if that would not also cause interop problems.
Nov 25 '08 #3
ShadowLocke
115 New Member
thanks for the input! I had already tried using unsigned shorts but it gave the same results. I forgot about the StructLayout attribute, so i played around with it for a little bit (found a greate resource here: VSJ | Articles | Mastering structs in C#)

But still was not able to get it through..seeing how the packing worked made me think for sure that was the problem. This is what I came up with:

Expand|Select|Wrap|Line Numbers
  1. [StructLayout(LayoutKind.Explicit, Size=16, Pack=1)]
  2.         struct MyGuid
  3.         {
  4.             [FieldOffset(0)]
  5.             public Int32 Data1;
  6.             [FieldOffset(4)]
  7.             public ushort Data2;
  8.             [FieldOffset(6)]
  9.             public ushort Data3;
  10.             [FieldOffset(8)]
  11.             public Byte Data4_1;
  12.             [FieldOffset(9)]
  13.             public Byte Data4_2;
  14.             [FieldOffset(10)]
  15.             public Byte Data4_3;
  16.             [FieldOffset(11)]
  17.             public Byte Data4_4;
  18.             [FieldOffset(12)]
  19.             public Byte Data4_5;
  20.             [FieldOffset(13)]
  21.             public Byte Data4_6;
  22.  
  23.             [FieldOffset(14)]
  24.             public ushort Data4_7_8;//Same number of bytes?
  25.             //public Byte Data4_7;
  26.             //public Byte Data4_8;
  27.         }
Still no dice..I wonder is there some way I can debug and see exactly what is being passed in memory? i.e. Looking at a hexdump of somekind? (I'm currently using VS2008 if it has the feature im unaware)
Nov 25 '08 #4
mldisibio
190 Recognized Expert New Member
I don't have VS08 installed, but in 05 during debugging there is an option from the Main Menu -> Debug -> Windows -> Disassembly or Memory or Registers.
Nov 25 '08 #5
ShadowLocke
115 New Member
Awesome! Exactly what i was looking for. Doing this let me see in memory what the problem was..though it still doesnt make sense..

The first example MyGuid goes through as:
00 00 00 00 00 00 00 00 C0 00 00 00 00 00 00 46

The second as:
00 00 00 00 00 00 00 00 C0 00 00 00 00 00 46 00

It was storing it backwards..
If i change the line:

Expand|Select|Wrap|Line Numbers
  1. g.Data4_7_8 = 70;
to:
Expand|Select|Wrap|Line Numbers
  1. g.Data4_7_8 = 17920;
(17920 = 0x4600)

It works..computer s are fun. Anyway..i thought only strings were held in memory backwards..i didnt realize other datatypes were as well
Nov 25 '08 #6
Plater
7,872 Recognized Expert Expert
.NET's CLR always uses the same byte-wise endian, regardless of what the underlying system byte-wise endian is.
Which usually means it's opposite of unmanaged code.
Nov 25 '08 #7
mldisibio
190 Recognized Expert New Member
So does this work?

Expand|Select|Wrap|Line Numbers
  1. // puts 0x4600 to rightmost bits 0x0046
  2. g.Data4_7_8 = (short)((70 << 8) & 0xFFFF);
  3.  
such that you could write:
Expand|Select|Wrap|Line Numbers
  1. Int16 lastTwoBytesAsShort = 70;
  2. g.Data4_7_8 = (short)((lastTwoBytesAsShort << 8) & 0xFFFF);
I guess since your original was two separate bytes, you are expecting the second to last byte (Data4_7) to always have a value of 0x00 and the actual bits of the short to be in the range of Byte? Otherwise, and this is getting confusing, if you have two shorts each with byte values, you could stuff the final short something like this:
Expand|Select|Wrap|Line Numbers
  1. Int16 data7 = 255;
  2. Int16 data8 = 70;
  3. // writes ff 00 46 00 as ff 46
  4. g.Data4_7_8 = (short)(data7 | ((data8 << 8) & 0xFFFF));
Nov 25 '08 #8
ShadowLocke
115 New Member
@mldisibio

Using the shift works (70 << 8 == 17920) Why do put "& 0xFFFF" though?

(The last one would not work because we are expecting 0x00 for the second to last byte [were expecting the iunknown guid "00000000-0000-0000-C000-000000000046"])
Nov 26 '08 #9
mldisibio
190 Recognized Expert New Member
I believe "& 0xFFFF" ensures the registers are cleared correctly.
I have followed the code of others who are much more familiar with bit-shifting than I am, including classes in MS Rotor code where bit shifting was done. However, maybe I missed the true purpose of doing it.
Nov 26 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
6310
by: | last post by:
When I execute the following (with an OleDBDataAdapter), wanting to add a row to a visual foxpro table: myrow= datasetTarget.Tables(0).NewRow 'fill all columns here like.. row(i)= myvalue ' then datasetTarget.Tables(0).Rows.Add(myrow) dataAdapterTarget.Update(datasetTarget.Tables(0)) '*
5
13279
by: Brian Reed | last post by:
I have a class that I want to serialize to an XML string. I want the XML to serialize to utf-8 encoding. When I serialize to an XML file, the data looks great. When I try to serialize to a String (ala StringBuilder) I get utf-16 and instead of the parenthesis (") I get a slash and then a " (\") which makes sense when looking at a character in...
2
4163
by: David Union | last post by:
Hi. I'm posting this here because I don't know exactly what the best group is. This is for an aspx page with Visual Basic as the code-behind page. I am doing very simple code... in the middle of an http request, i set a filename (with path) and do a Response.WriteFile(filenamewithpath) then Response.End(). I have tried Response.Clear()...
5
9785
by: Robin Tucker | last post by:
I need to marshal an IntPtr (which I've got from GlobalLock of an HGLOBAL) into a byte array. I know the size of the array required and I've got a pointer to the blob, but I can't see how to copy the memory across. Using Marshal.PtrStructure doesn't work - it says my byte() array is not blittable! (byte is a blittable type however). Cannot...
9
12673
by: Charles Law | last post by:
Suppose I have a structure Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure I want to convert this into a byte array where
6
2751
by: Dennis | last post by:
I was trying to determine the fastest way to build a byte array from components where the size of the individual components varied depending on the user's input. I tried three classes I built: (1) using redim arrays to add to a normal byte array (2) using an ArrayList and finally (3) using a memorystream. These three classes are listed below...
4
2206
by: Frederick Gotham | last post by:
What do you think of the following code for setting and retrieving the value of bytes in an unsigned integer? The least significant bit has index 0, then the next least significant bit has index 1, and so on. The code computes at runtime the byte-order of the unsigned integer, but alas it would be better if it could be determined at...
5
9576
by: vtjumper | last post by:
I'm building a C# interface to an existing messaging system. The messaging system allows values of several types to be sent/recieved over the interface. What I want to do is use a generic class to produce values in the system. For instance I could create class MsgGenericValue<UInt16>() which would represent an unsigned value on the...
2
7189
by: O.B. | last post by:
When using Marshal to copy data from a byte array to the structure below, only the first byte of the "other" array is getting copied from the original byte array. What do I need to specify to get Marshal.PtrToStructure to copy the all the data into the "other" array? unsafe public struct DeadReckoning {
0
7432
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7943
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7456
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7786
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6022
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5359
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.