オーケー、プロプライエタリ サーバーからの応答を簡単に解析しようとしているときに、まったく同じことを念頭に置いていました。これは、特定のケースに合わせて調整された単純な例です。
まず、これをずっと簡単にするために、いくつかの拡張機能が必要です。これを行うには、.NET 3.5 以降を使用する必要があることに注意してください。または、こちらの回答を参照してください。
さて、ここに私が拡張クラスのために取り組んでいるものがあります:
public static class EndianExtensions {
/// <summary>
/// Convert the bytes to a structure in host-endian format (little-endian on PCs).
/// To use with big-endian data, reverse all of the data bytes and create a struct that is in the reverse order of the data.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="buffer">The buffer.</param>
/// <returns></returns>
public static T ToStructureHostEndian<T>(this byte[] buffer) where T : struct {
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T stuff = (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return stuff;
}
/// <summary>
/// Converts the struct to a byte array in the endianness of this machine.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="structure">The structure.</param>
/// <returns></returns>
public static byte[] ToBytesHostEndian<T>(this T structure) where T : struct {
int size = Marshal.SizeOf(structure);
var buffer = new byte[size];
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.StructureToPtr(structure, handle.AddrOfPinnedObject(), true);
handle.Free();
return buffer;
}
public static Dictionary<string, string> GetTypeNames<T>(this T structure) where T : struct {
var properties = typeof(T).GetFields();
var dict = new Dictionary<string, string>();
foreach (var fieldInfo in properties) {
string[] words = fieldInfo.Name.Split('_');
string friendlyName = words.Aggregate(string.Empty, (current, word) => current + string.Format("{0} ", word));
friendlyName = friendlyName.TrimEnd(' ');
dict.Add(fieldInfo.Name, friendlyName);
}
return dict;
}
}
(上記の一部は CodeProject のソースからサンプリングされたものであり、すべてCPOL ライセンスの下にあることに注意してください)
注意すべきもう 1 つの重要な点は、GetTypeNames
スペースが必要な場所に CamelCaps とアンダースコアを使用する場合、拡張子を使用してプロパティのわかりやすい名前を取得できることです。
これを機能させるための最後の重要な部分 (少なくとも、私の特定のケースでは) は、構造体をreverseで宣言することです。これは、サーバーがビッグ エンディアンを使用しているためです。エンディアンを変更して、または変更せずに試してみてください。
実際にこれを使用するには、次のようにします。
- 構造体を宣言します。送信する前にビッグエンディアンにする必要があったため、すべて逆になっています。
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Foo {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string User_Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Password;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Bar {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Password;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string User_Name;
};
上記は、送信データ バッファーと受信データ バッファーの実際の内容が異なるように定義されていることを前提としているため、これらの構造体の 1 つを定義するだけで済みます。これらは逆の順序で指定されていることに注意してください。繰り返しますが、これはビッグ エンディアン形式で送信する必要があったためです。
あとは、送信する構造体を作成するだけです。
// buffer for storing our received bytes
var barBuf = new byte[64];
// struct that we're sending
var fuz = new Foo {
User_Name = "username",
Password = "password"
};
// get the byte equivalent of fuz
var fuzBytes = fuz.ToBytesHostEndian().Reverse().ToArray();
// simulates sock.send() and sock.receive()
// note that this does NOT simulate receiving big-endian data!!
fuzBytes.CopyTo(barBuf, 0);
// do the conversion from bytes to struct
barBuf = barBuf.Reverse().ToArray();
// change this to ToStructureHostEndian<Bar>() if receiving big endian
var baz = barBuf.ToStructureHostEndian<Foo>();
// get the property names, friendly and non-friendly
var bazDict = baz.GetTypeNames();
// change this to typeof(Bar) if receiving big endian
var bazProps = typeof(Foo).GetFields();
// loop through the properties array
foreach (var fieldInfo in bazProps) {
var propName = fieldInfo.Name;
// get the friendly name and value
var fieldName = bazDict[propName];
var value = fieldInfo.GetValue(baz);
// do what you want with the values
Console.WriteLine("{0,-15}:{1,10}", fieldName, value);
}
sock.Send()
を使用しておよびsock.Receive()
コマンドをシミュレートすることによってCopyTo()
、 でビッグ エンディアン配列が生成されないことに注意することが重要barBuf
です。それに応じてコードを変更しましたが、これを使用してビッグ エンディアン データを受信する場合は、コードに示されている行を変更するだけです。
これが役立つことを願っています。この情報は複数の情報源に散らばっていたため、自分自身を理解するのにかなりの時間がかかりました.