如何把csharp里面的class/struct转换成byte array

本文介绍了一个实用的C#类,能够轻松实现类或结构体与bytearray之间的相互转换,对于socket编程尤其有用。该方法利用了.NET Framework的Marshal类来完成内存操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
使用下面的这个类,可以很方便的把类/结构转换成byte array. 在进行socke编程的时候很有用。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;

  5. class CommonConvertion
  6. {
  7. public static byte[] StructureToByteArray(object obj)
  8. {
  9. int Length = Marshal.SizeOf(obj);
  10. byte[] bytearray = new byte[Length];
  11. IntPtr ptr = Marshal.AllocHGlobal(Length);
  12. Marshal.StructureToPtr(obj, ptr, false);
  13. Marshal.Copy(ptr, bytearray, 0, Length);
  14. Marshal.FreeHGlobal(ptr);
  15. return bytearray;
  16. }

  17. public static void ByteArrayToStructure(byte[] bytearray, ref object obj)
  18. {
  19. int Length = Marshal.SizeOf(obj);
  20. IntPtr ptr = Marshal.AllocHGlobal(Length);
  21. Marshal.Copy(bytearray, 0, ptr, Length);
  22. obj = Marshal.PtrToStructure(ptr, obj.GetType());
  23. Marshal.FreeHGlobal(ptr);
  24. }
  25. }

using UnityEngine; using System; using System.Collections; //using System.Collections.Generic; using XLua; namespace LuaFramework { [LuaCallCSharp] public class ResourceManager : Manager { public static ResourceManager _instance; public LuaFunction onDestroy; private WWW _www; private LuaFunction onProgress; void Awake() { _instance = this; } public static ResourceManager Instance { get { return _instance; } } public void CreatUIObject(string UIPath, string objname, LuaFunction callBack = null) { #if UNITY_EDITOR if (!AppConst.UpdateMode) { string path = "datingui_" + AppConst.UIVersion.ToString() + "/" + UIPath + objname; UnityEngine.Object prefab = Resources.Load(path, typeof(GameObject)); if (prefab != null) { //GameObject obj = Instantiate(Resources.Load<GameObject>(path)); //if (obj != null) //{ GameObject obj = Instantiate(prefab) as GameObject; obj.transform.localScale = Vector3.one; obj.transform.localPosition = Vector3.zero; if (callBack != null) { callBack.Call(obj); } //} }else { if (callBack != null) { callBack.Call(null); } } }else { StartCoroutine(LoadObj(AppConst.FrameworkRoot + "/datingui_" + AppConst.UIVersion + "/" + UIPath + objname + ".u3d", objname, callBack)); } #else StartCoroutine(LoadObj(AppConst.FrameworkRoot + "/datingui_" + AppConst.UIVersion + "/" + UIPath + objname + ".u3d", objname, callBack)); #endif } public void CreatGameObject(string GameName, string path, string objname, LuaFunction callBack = null) { #if UNITY_EDITOR if (!AppConst.UpdateMode) { //try //{ GameObject obj = Instantiate(Resources.Load<GameObject>("gameui"+AppConst.UIVersion+"/" + GameName + "/" + path + objname)); obj.transform.localScale = Vector3.one; obj.transform.localPosition = Vector3.zero; if (callBack != null) { callBack.Call(obj); } //}catch (Exception ex) //{ // Debug.LogError(ex.Message); //} } else { string path_ = AppConst.FrameworkRoot + "/gameui" + AppConst.UIVersion + "/" + GameName + "/" + path + objname + ".u3d"; StartCoroutine(LoadObj(path_, objname, callBack)); } #else string path_ = AppConst.FrameworkRoot + "/gameui"+AppConst.UIVersion +"/" + GameName + "/" + path + objname + ".u3d"; StartCoroutine(LoadObj(path_, objname, callBack)); #endif } public void setProgressUpdate(LuaFunction callback) { onProgress = callback; } public void resetProgressUpdate() { onProgress = null; _www = null; } float jindus = 0.0f; void Update() { #if UNITY_ANDROID if (_www != null && onProgress != null) { onProgress.Call(_www.progress); //Debug.Log(www.progress); } #else //if (jindutiao) // jindutiao.value = jindus; if (onProgress != null) { onProgress.Call(jindus); //Debug.Log(www.progress); } #endif } IEnumerator LoadObj(string bundlePath, string ObjName, LuaFunction callBack = null) { AssetBundle built = null; #if UNITY_ANDROID string path_2 = "file:///" + bundlePath; WWW www = new WWW(@path_2); if (onProgress != null) { _www = www; } yield return www; if (www.error == null) { yield return built = www.assetBundle; } else { Debug.Log("www null-------- " + path_2); } #else string path_ = bundlePath; byte[] data = null;// = OpenFile.GetFileData(path_); if (System.IO.File.Exists(path_)) { System.IO.FileStream file_ = new System.IO.FileStream(path_, System.IO.FileMode.Open, System.IO.FileAccess.Read); data = new byte[file_.Length]; int redline = 0; int allnum = 0; while (true) { byte[] reddata = new byte[1024000]; redline = file_.Read(reddata, 0, (int)reddata.Length); if (redline <= 0) { jindus = 1.0f; break; } else { //Debug.LogError(redline); System.Array.Copy(reddata, 0, data, allnum, redline); allnum += redline; jindus = (float)allnum / (float)data.Length; } yield return null; } file_.Close(); file_.Dispose(); } if (data != null) { yield return built = AssetBundle.LoadFromMemory(data); } #endif if (built != null) { GameObject obj = Instantiate(built.LoadAsset(ObjName)) as GameObject; obj.transform.localScale = Vector3.one; obj.transform.localPosition = Vector3.zero; if (callBack != null) { callBack.Call(obj); } built.Unload(false); }else { if (callBack != null) { callBack.Call(null); } } #if UNITY_ANDROID www.Dispose(); #endif } void OnDestroy() { if (onDestroy != null) { onDestroy.Call(); } } } }这个是UNITY5.3版本LUA代码,运行时的报错的日志文件在下面,请帮我检查一下代码并修改,但是不要影响到别的文件调用,-----CompilerOutput:-stderr---------- Assets/Scripts/Manager/ResourceManager.cs(16,49): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(16,62): error CS1519: Unexpected symbol `?' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(16,98): error CS1519: Unexpected symbol `(' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(46,60): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(46,74): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(46,80): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(47,56): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(47,70): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(47,76): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(48,57): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(48,68): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(48,74): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(64,27): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(73,27): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(82,42): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(82,13): warning CS0642: Possible mistaken empty statement Assets/Scripts/Manager/ResourceManager.cs(105,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(106,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(110,35): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(112,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(113,26): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(127,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(140,31): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(145,95): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(151,33): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(181,14): error CS1519: Unexpected symbol `if' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(181,25): error CS1519: Unexpected symbol `!=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(184,28): error CS1519: Unexpected symbol `return' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(184,42): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(186,39): error CS1041: Identifier expected Assets/Scripts/Manager/ResourceManager.cs(187,55): error CS1018: Keyword `this' or `base' expected Assets/Scripts/Manager/ResourceManager.cs(186,17): error CS1520: Class, struct, or interface method must have a return type Assets/Scripts/Manager/ResourceManager.cs(189,30): error CS1519: Unexpected symbol `(' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(191,16): error CS1518: Expected `class', `delegate', `enum', `interface', or `struct' Assets/Scripts/Manager/ResourceManager.cs(197,29): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(230,27): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(229,13): warning CS0642: Possible mistaken empty statement Assets/Scripts/Manager/ResourceManager.cs(221,22): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(236,21): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(253,14): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(259,5): error CS8025: Parsing error
07-08
public static string WordsToString(int[] words) { if (words == null || words.Length == 0) return string.Empty; var sb = new StringBuilder(); foreach (int word in words) { // 提取低8位(LSB)→ 第一个字符 byte lowByte = (byte)(word & 0xFF); if (lowByte == 0) break; // 遇到空字符终止 sb.Append((char)lowByte); // 提取高8位(MSB)→ 第二个字符 byte highByte = (byte)((word >> 8) & 0xFF); if (highByte == 0) break; // 遇到空字符终止 sb.Append((char)highByte); } return sb.ToString(); } public static int[] StringToWords(string str, int minLength = 0) { if (string.IsNullOrEmpty(str)) str = "\0"; // 空字符串需包含终止符 // 转换为ASCII字节数组(仅支持ASCII字符) byte[] bytes = Encoding.ASCII.GetBytes(str); // 添加字符串终止符 \0(确保以0x0000结尾) byte[] withNull = new byte[bytes.Length + 1]; Buffer.BlockCopy(bytes, 0, withNull, 0, bytes.Length); withNull[bytes.Length] = 0; // 确保字节数组长度为偶数(每2字节=1个字) if (withNull.Length % 2 != 0) { Array.Resize(ref withNull, withNull.Length + 1); withNull[withNull.Length - 1] = 0; } // 按小端序组合:[低地址字节, 高地址字节] → [LSB, MSB] int[] words = new int[withNull.Length / 2]; for (int i = 0; i < withNull.Length; i += 2) { words[i / 2] = withNull[i] | (withNull[i + 1] << 8); } // 按需填充到最小长度(如PLC固定数组长度) if (minLength > 0 && words.Length < minLength) { Array.Resize(ref words, minLength); for (int i = words.Length; i < minLength; i++) words[i] = 0; } return words; } 以上为在C#和欧姆龙PLC通讯协议中, int[]数组和string类型相互转换的函数,麻烦进行大量数据的验证以确保其转换逻辑是正确的;我需要使用在PLC读写前后的数据转换逻辑里
最新发布
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值