(精华)2020年6月27日 C#类库 共享内存帮助类

举报
愚公搬代码 发表于 2021/10/18 23:50:58 2021/10/18
【摘要】 using System; using System.Reflection; using System.Runtime.InteropServices; namespace Core.Util { ...
using System;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Core.Util
{
    /// <summary>
    /// 共享内存
    /// </summary>
    public class ShareMenmory
    {
        #region 导入类库及方法
        [DllImport("user32.dll", CharSet = CharSet.Auto)]

        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);



        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]

        public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi, uint dwMaxSizeLow, string lpName);



        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]

        public static extern IntPtr OpenFileMapping(int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);



        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]

        public static extern IntPtr MapViewOfFile(IntPtr hFileMapping, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);



        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]

        public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);



        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]

        public static extern bool CloseHandle(IntPtr handle);



        [DllImport("kernel32", EntryPoint = "GetLastError")]

        public static extern int GetLastError();



        const int ERROR_ALREADY_EXISTS = 183;



        const int FILE_MAP_COPY = 0x0001;

        const int FILE_MAP_WRITE = 0x0002;

        const int FILE_MAP_READ = 0x0004;

        const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;



        const int PAGE_READONLY = 0x02;

        const int PAGE_READWRITE = 0x04;

        const int PAGE_WRITECOPY = 0x08;

        const int PAGE_EXECUTE = 0x10;

        const int PAGE_EXECUTE_READ = 0x20;

        const int PAGE_EXECUTE_READWRITE = 0x40;



        const int SEC_COMMIT = 0x8000000;

        const int SEC_IMAGE = 0x1000000;

        const int SEC_NOCACHE = 0x10000000;

        const int SEC_RESERVE = 0x4000000;



        const int INVALID_HANDLE_VALUE = -1;
        #endregion

        IntPtr m_hSharedMemoryFile = IntPtr.Zero;

        IntPtr m_pwData = IntPtr.Zero;//共享内存地址

        public bool m_bAlreadyExist = false;

        bool m_bInit = false;

        long m_MemSize = 0;

        public ShareMenmory(string strName, long lngSize)
        {
            if (OpenExists(strName, lngSize) == false)
                Init(strName, lngSize);
        }
        ~ShareMenmory()
        {
            Close();
        }

        //初始化内存
        public void Init(string strName, long lngSize)
        {
            m_MemSize = lngSize;
            if (strName.Length > 0)
            {
                //创建内存共享体(INVALID_HANDLE_VALUE)
                m_hSharedMemoryFile = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)PAGE_READWRITE, 0, (uint)lngSize, strName);
                if (m_hSharedMemoryFile == IntPtr.Zero)
                {
                    m_bAlreadyExist = false;
                    m_bInit = false;
                }
                else
                {
                    if (GetLastError() == ERROR_ALREADY_EXISTS)  //已经创建

                    {
                        m_bAlreadyExist = true;
                    }
                    else

                    {
                        m_bAlreadyExist = false;
                    }
                }
                //创建内存映射
                try
                {
                    m_pwData = MapViewOfFile(m_hSharedMemoryFile, FILE_MAP_WRITE, 0, 0, 0);

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                if (m_pwData == IntPtr.Zero)
                {
                    m_bInit = false;
                    CloseHandle(m_hSharedMemoryFile);
                }
                else
                {
                    m_bInit = true;
                    m_bAlreadyExist = true;
                }
            }
        }

        /// <summary>
        /// 获取共享内存
        /// </summary>
        /// <param name="mapName">内存名</param>
        /// <param name="Size">大小</param>
        public bool OpenExists(string mapName, long Size)
        {
            try
            {
                m_hSharedMemoryFile = OpenFileMapping(0x0002, true, mapName);
                m_pwData = MapViewOfFile(m_hSharedMemoryFile, 0x0002, 0, 0, (uint)Size);

                if (m_hSharedMemoryFile == IntPtr.Zero || m_pwData == IntPtr.Zero)
                    return false;
                m_MemSize = Size;
                m_bInit = true;
                m_bAlreadyExist = true;

                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
        }

        //关闭共享内存

        public void Close()
        {

            if (m_bInit)

            {
                UnmapViewOfFile(m_pwData);

                CloseHandle(m_hSharedMemoryFile);
            }
        }
        /// <summary>
        /// 从共享内存读数据
        /// </summary>
        /// <param name="lngSize">数据长度</param>
        /// <param name="ofset">指针偏移量</param>
        /// <returns></returns>
        public byte[] Read(int lngSize, int ofset)
        {
            byte[] bytData = new byte[lngSize];
            Marshal.Copy(m_pwData + ofset, bytData, 0, lngSize);

            return bytData;
        }

        /// <summary>
        /// 将数据写入内存中
        /// </summary>
        /// <param name="bytData">需要写入的数据</param>
        /// <param name="offset">目的内存地址偏移量</param>
        public void Write(byte[] bytData, int offset)
        {
            Marshal.Copy(bytData, 0, m_pwData + offset, bytData.Length);
        }
    }

    /// <summary>
    /// 共享内存之操作泛型实体类
    /// </summary>
    /// <typeparam name="T">泛型参数</typeparam>
    public class ShareMenmory<T>
    {
        #region 常量
        const int ERROR_ALREADY_EXISTS = 183;

        const int FILE_MAP_COPY = 0x0001;

        const int FILE_MAP_WRITE = 0x0002;

        const int FILE_MAP_READ = 0x0004;

        const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;



        const int PAGE_READONLY = 0x02;

        const int PAGE_READWRITE = 0x04;

        const int PAGE_WRITECOPY = 0x08;

        const int PAGE_EXECUTE = 0x10;

        const int PAGE_EXECUTE_READ = 0x20;

        const int PAGE_EXECUTE_READWRITE = 0x40;



        const int SEC_COMMIT = 0x8000000;

        const int SEC_IMAGE = 0x1000000;

        const int SEC_NOCACHE = 0x10000000;

        const int SEC_RESERVE = 0x4000000;



        const int INVALID_HANDLE_VALUE = -1;
        #endregion

        IntPtr m_hSharedMemoryFile = IntPtr.Zero;//共享内存空间指针

        IntPtr m_pwData = IntPtr.Zero;//共享内存地址

        public bool m_bAlreadyExist = false;

        bool m_bInit = false;

        long m_MemSize = 0;

        private int entityLength=0;
        public ShareMenmory(string strName, long lngSize)
        {
            if (OpenExists(strName, lngSize) == false)
                Init(strName, lngSize);

            Type t = typeof(T);
            object obj = Activator.CreateInstance(t);
            MethodInfo method = t.GetMethod("getLength");
            entityLength = (int)method.Invoke(obj, null);
        }
        ~ShareMenmory()
        {
            Close();
        }

        //初始化内存
        public void Init(string strName, long lngSize)
        {
            m_MemSize = lngSize;
            if (strName.Length > 0)
            {
                //创建内存共享体(INVALID_HANDLE_VALUE)
                m_hSharedMemoryFile = ShareMenmory.CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)PAGE_READWRITE, 0, (uint)lngSize, strName);
                if (m_hSharedMemoryFile == IntPtr.Zero)
                {
                    m_bAlreadyExist = false;
                    m_bInit = false;
                }
                else
                {
                    if (ShareMenmory.GetLastError() == ERROR_ALREADY_EXISTS)  //已经创建

                    {
                        m_bAlreadyExist = true;
                    }
                    else

                    {
                        m_bAlreadyExist = false;
                    }
                }
                //创建内存映射
                try
                {
                    m_pwData = ShareMenmory.MapViewOfFile(m_hSharedMemoryFile, FILE_MAP_WRITE, 0, 0, 0);

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                if (m_pwData == IntPtr.Zero)
                {
                    m_bInit = false;
                    ShareMenmory.CloseHandle(m_hSharedMemoryFile);
                }
                else
                {
                    m_bInit = true;
                    m_bAlreadyExist = true;
                }
            }
        }

        /// <summary>
        /// 获取共享内存
        /// </summary>
        /// <param name="mapName">内存名</param>
        /// <param name="Size">大小</param>
        public bool OpenExists(string mapName, long Size)
        {
            try
            {
                m_hSharedMemoryFile = ShareMenmory.OpenFileMapping(0x0002, true, mapName);
                m_pwData = ShareMenmory.MapViewOfFile(m_hSharedMemoryFile, 0x0002, 0, 0, (uint)Size);

                if (m_hSharedMemoryFile == IntPtr.Zero || m_pwData == IntPtr.Zero)
                    return false;
                m_MemSize = Size;
                m_bInit = true;
                m_bAlreadyExist = true;

                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
        }

        //关闭共享内存

        public void Close()
        {

            if (m_bInit)

            {
                ShareMenmory.UnmapViewOfFile(m_pwData);

                ShareMenmory.CloseHandle(m_hSharedMemoryFile);
            }
        }
        /// <summary>
        /// 从共享内存读数据
        /// </summary>
        /// <param name="lngSize">数据长度</param>
        /// <param name="ofset">指针偏移量</param>
        /// <returns></returns>
        public byte[] Read(int lngSize, int ofset)
        {
            byte[] bytData = new byte[lngSize];
            Marshal.Copy(m_pwData + ofset, bytData, 0, lngSize);

            return bytData;
        }

        /// <summary>
        /// 将数据写入内存中
        /// </summary>
        /// <param name="bytData">需要写入的数据</param>
        /// <param name="offset">目的内存地址偏移量</param>
        public void Write(byte[] bytData, int offset)
        {
            Marshal.Copy(bytData, 0, m_pwData + offset, bytData.Length);
        }
        
        /// <summary>
        /// 获取URL
        /// </summary>
        /// <param name="index">所需要获取URL的索引序号</param>
        /// <returns></returns>
        public string GetUrl(int index)
        {
            int offset = 1 + index * (entityLength + 1)+8;
            return Extention.ToString(Read(200, offset)).Trim();
        }

        /// <summary>
        /// 保存URL
        /// </summary>
        /// <param name="index">保存的位置(索引序号)</param>
        /// <param name="url">URL</param>
        public void SetUrl(int index, string url)
        {
            int offset = 1 + index * (entityLength + 1) + 8;
            Write(url.ToBytes(), offset);
        }

        /// <summary>
        /// 获取状态
        /// </summary>
        /// <param name="index">索引序号</param>
        /// <returns></returns>
        public string GetState(int index)
        {
            int offset = 1 + index * (entityLength + 1) + entityLength-2;
            return Extention.ToString(Read(1, offset));
        }

        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="index">索引序号</param>
        /// <param name="state">状态(0为未爬取,1为已经爬取)</param>
        public void SetState(int index,int state)
        {
            int offset = 1 + index * (entityLength + 1) + entityLength - 2;
            Write(state.ToString().ToBytes(),offset);
        }

        /// <summary>
        /// 保存实体类
        /// </summary>
        /// <param name="index">索引序号</param>
        /// <param name="t">实体类型</param>
        public void SetEntity(int index,T t)
        {
            int offset = index*entityLength;
            Write(t.EntityToJson().ToBytes(), offset);
        }

        public T GetEntity(int index)
        {
            string str = Extention.ToString(Read(entityLength, index * entityLength));
            return str.ToEntity<T>();
        }
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476

文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。

原文链接:codeboy.blog.csdn.net/article/details/106983089

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。