C# Net/Win32 内存操作

这篇博客介绍了C#中进行内存操作的方法,包括LocalAlloc、GlobalAlloc和VirtualAlloc三种分配内存的方式。同时,文章提醒在使用这些方法时需要注意不能读写对象类型,并且不应在Net 4.5环境下操作Net Byte[]。此外,还提到了SetProcessWorkingSetSize函数用于内存优化,但过度优化可能导致系统将物理内存转移到虚拟内存,反而使性能下降。

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

使用方法:

结果如下:

 

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace std
{
    public partial class Memory : Object
    {

        [DllImportAttribute("kernel32.dll", EntryPoint = "WriteProcessMemory")]
        [return: MarshalAsAttribute(UnmanagedType.Bool)]
        static extern bool WriteProcessMemory(
            [InAttribute()] IntPtr hProcess,
            [InAttribute()] IntPtr lpBaseAddress,
            [InAttribute()] byte[] lpBuffer,
            int nSize,
            IntPtr lpNumberOfBytesWritten
            );

        [DllImportAttribute("kernel32.dll", EntryPoint = "ReadProcessMemory")]
        [return: MarshalAsAttribute(UnmanagedType.Bool)]
        static extern bool ReadProcessMemory(
            [InAttribute()] IntPtr hProcess,
            [InAttribute()] IntPtr lpBaseAddress,
            [InAttribute()] IntPtr lpBuffer,
            uint nSize,
            IntPtr lpNumberOfBytesRead
            );

        [DllImportAttribute("kernel32.dll", EntryPoint = "OpenProcess")]
        static extern IntPtr OpenProcess(
            uint dwDesiredAccess,
            [MarshalAsAttribute(UnmanagedType.Bool)] bool bInheritHandle,
            uint dwProcessId
            );

        [DllImportAttribute("kernel32.dll", EntryPoint = "GetCurrentProcessId")]
        static extern uint GetCurrentProcessId();

        [DllImportAttribute("kernel32.dll", EntryPoint = "CloseHandle")]
        [return: MarshalAsAttribute(UnmanagedType.Bool)]
        static extern bool CloseHandle(
            [InAttribute()] IntPtr hObject
            );


        [DllImportAttribute("ntdll.dll", EntryPoint = "RtlCopyMemory")]
        static extern uint RtlCompareMemory(  
            [InAttribute()] IntPtr Source1,
            [InAttribute()] IntPtr Source2,
            uint Length
            );

        [DllImportAttribute("Psapi.dll", EntryPoint = "GetModuleFileNameEx")]
        static extern uint GetModuleFileNameExA(
            [InAttribute()] IntPtr hProcess,
            [InAttribute()] IntPtr hModule, 
            [OutAttribute(), MarshalAsAttribute(UnmanagedType.LPStr)] StringBuilder lpFilename,
            [InAttribute()] uint nSize
                    );

        [DllImpo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值