Access memory address in c#

前端 未结 4 1242
孤城傲影
孤城傲影 2021-02-04 19:34

I am interfacing with an ActiveX component that gives me a memory address and the number of bytes.

How can I write a C# program that will access the bytes starting at

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 20:02

    I highly suggest you use an IntPtr and Marshal.Copy. Here is some code to get you started. memAddr is the memory address you are given, and bufSize is the size.

    IntPtr bufPtr = new IntPtr(memAddr);
    byte[] data = new byte[bufSize];
    Marshal.Copy(bufPtr, data, 0, bufSize);
    

    This doesn't require you to use unsafe code which requires the the /unsafe compiler option and is not verifiable by the CLR.

    If you need an array of something other than bytes, just change the second line. Marshal.Copy has a bunch of overloads.

提交回复
热议问题