/// <summary> /// 共有メモリにオブジェクトを書き込みます。 /// </summary> /// <param name="obj">書き込むシリアライズ可能なオブジェクト</param> /// <param name="addr">書き込み先共有メモリの 0 から始まるアドレス</param> public void PutObject(object obj, int addr) { // 排他 - 最大1秒待つ Mutex mutex = new Mutex(false, MUTEX_NAME + "_" + sharedName); mutex.WaitOne(1000, false); try { SharedObjectBag bag = new SharedObjectBag(); bag.Object = obj; MemoryStream ms = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, bag); byte[] buf = ms.ToArray(); byte[] siz = new byte[2]; int wsiz = buf.Length; siz[0] = (byte)(wsiz / 0x100); siz[1] = (byte)(wsiz & 0xff); putBytes(siz, addr + SMEM_HEADER_LENGTH, 0, 2); putBytes(buf, addr + SMEM_HEADER_LENGTH + 2, 0, wsiz); UpdCountup(); } catch (Exception es) { throw es; } finally { mutex.ReleaseMutex(); } }
/// <summary> /// 共有メモリからオブジェクトを読み込みます。 /// </summary> /// <param name="addr">読み込み元共有メモリの 0 から始まるアドレス</param> /// <returns>読み込むオブジェクト</returns> public object GetObject(int addr) { byte[] siz = new byte[2]; getBytes(ref siz, addr + SMEM_HEADER_LENGTH, 0, 2); int wsiz = siz[0] * 0x100 + siz[1]; byte[] buf = new byte[wsiz]; getBytes(ref buf, addr + SMEM_HEADER_LENGTH + 2, 0, wsiz); MemoryStream ms = new MemoryStream(buf); IFormatter formatter = new BinaryFormatter(); SharedObjectBag bag = (SharedObjectBag)formatter.Deserialize(ms); lastUpdCount = GetUpdCount(); return(bag.Object); }