Search code examples
.netwinapimemoryreadprocessmemoryinteropservices

Marshal.Copy vs ReadProcessMemory / WriteProcessMemory win32 api - in the same process


I am wondering if someone can outline the main differences, pro-s and con-s of using ReadProcessMemory/WriteProcessMemory over Marshal.Copy in Windows .NET (C#/VB.net) applications to read from / write to the application's process' memory (not memory of other processes). In particular for operations involving arbitrary addresses in process' memory and dealing with memory block as byte arrays (i.e. reading/writing raw data).

Would Marshal.Copy work in all cases where ReadProcessMemory/WriteProcessMemory works, or is it more limiting?

Does Marshal.Copy's implementation use ReadProcessMemory/WriteProcessMemory APIs internally?

To clarify: I am talking about reading from / writing to the calling (owning) process's memory only, not the memory of other processes!

Thanks.


Solution

  • ReadProcessMemory and WriteProcessMemory are native Win32 APIs that allow you to read and write from and to the memory of a different processes. You only ever need to use those APIs when trying to read and write memory in a different process. As you may imagine, they are not often used in routine development.

    Marshal.Copy is used to copy between managed and unmanaged memory, but within the same process.

    Would Marshal.Copy work in all cases where ReadProcessMemory/WriteProcessMemory works, or is it more limiting?

    No, Marshal.Copy it is limited to operating within a single process.

    Does Marshal.Copy's implementation use ReadProcessMemory/WriteProcessMemory APIs internally?

    No.

    To clarify: I am talking about reading from / writing to the calling (owning) process's memory only, not the memory of other processes!

    In which case, ReadProcessMemory and WriteProcessMemory are simply not pertinent to your needs.