While Creating a Array Inside a Structure , Does that Structure Contain Directly the Value of Array or the Memory reference to that array?

旧巷老猫 提交于 2019-12-12 01:15:29

问题


I am creating an array as below:

public struct Smb_Parameters
        {
            public byte WordCount;
            public ushort[] Words;
        }

While I assign the values Like below:

Smb_Parameters smbParameter = new Smb_Parameters();
smbParameter.WordCount = 0;
string words= "NT LM 0.12";
smbParameter.Words = Encoding.ASCII.GetBytes(name);

In the above assignment smbParameter.WordCount contains the value 0 but does smbParameter.Words contains directly the values(Arry of byteS) or memory reference to the location that contains the values?

Edit 1:

I want to send a packet to the server . For that I need to convert Smb_Parameters object to array using the following code:

int len = Marshal.SizeOf(Smb_Parameters);
 byte[] arr = new byte[len];
 IntPtr ptr = Marshal.AllocHGlobal(len);
 Marshal.StructureToPtr(Smb_Parameters, ptr, true);
 Marshal.Copy(ptr, arr, 0, len);
 Marshal.FreeHGlobal(ptr);

回答1:


Unless you use fixed-size buffers in unsafe code, it will be a reference. In general, it doesn't matter whether a variable is contained within a struct or a class - or indeed whether it's a local variable: the type of the variable decides whether the value is a reference or whether it contains the data directly. Aside from the fixed-size buffers I've mentioned, arrays are always reference types in .NET.

(There's also stackalloc which looks a bit like an array allocation - it allocates a block of memory on the stack. Again, this is only for use in unsafe code, and very rarely encountered in my experience.)

In the example you've given (suitably adjusted to make it compile) Words would definitely be a reference. In particular, if you assign the value to refer to a particular array and then change the contents of that array, the changes will be visible via the struct's variable.

(I'd also strongly recommend that you don't have public fields or mutable value types. Hopefully this was just for the sake of an example though :)

EDIT: To answer the updated question, don't send data like that. It's a horribly fragile way of serializing anything. There are various better options:

  • Use .NET binary serialization (also somewhat fragile in terms of versioning, and not cross-platform)
  • Use XML serialization (probably overkill in this case)
  • Use a third-party serialization framework (e.g. Thrift or Protocol Buffers)
  • Hand-roll serialization with a "ToByteArray" or "WriteToStream" method in your class which serializes each value explicitly. You might want to use BinaryWriter for this.


来源:https://stackoverflow.com/questions/3437731/while-creating-a-array-inside-a-structure-does-that-structure-contain-directly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!