c# - How to get an IntPtr to access the view of a MemoryMappedFile? -
is there way direct intptr
data in memorymappedfile? have large data block high frequency change , don't want copy it
no, not intptr, doesn't anyway. can byte*
, can cast @ access actual data type. , can cast intptr if have to. having use unsafe
keyword quite intentional.
create memorymappedviewaccessor create view on mmf. use acquirepointer() method of safememorymappedviewhandle property obtain byte*.
a sample program demonstrates usage , shows various pointer shenanigans:
using system; using system.diagnostics; using system.runtime.interopservices; class program { static unsafe void main(string[] args) { using (var mmf = system.io.memorymappedfiles.memorymappedfile.createnew("test", 42)) using (var view = mmf.createviewaccessor()) { byte* poke = null; view.safememorymappedviewhandle.acquirepointer(ref poke); *(int*)poke = 0x12345678; debug.assert(*poke == 0x78); debug.assert(*(poke + 1) == 0x56); debug.assert(*(short*)poke == 0x5678); debug.assert(*((short*)poke + 1) == 0x1234); debug.assert(*(short*)(poke + 2) == 0x1234); intptr ipoke = (intptr)poke; debug.assert(marshal.readint32(ipoke) == 0x12345678); *(poke + 1) = 0xab; debug.assert(marshal.readint32(ipoke) == 0x1234ab78); view.safememorymappedviewhandle.releasepointer(); } } }
Comments
Post a Comment