.net - Get Win32 HANDLE from MemoryMappedFile -


what property or method (if any) provide win32 handle .net memorymappedfile?

i have unmanaged c++ code reads , writes c-style files, such stdin , stdout. want create memorymappedfile using memorymappedfile::createnew win32 handle can converted file* use in unmanaged c++. see memorymappedviewaccessor::safememorymappedviewhandle , safehandle , other possibilities don't find stating (or showing example) handle can used win32 handle in c/c++ program. not sure provides win32 handle. there other possibilities, such using windows api , no .net asking if can done using memorymappedfile, sure can using windows api if can't done using memorymappedfile.

update: following code @michaelgunter converted c++. see comment hans passant, says won't work , not. handle returned safehandle->dangerousgethandle() seems valid when call _open_osfhandle convert handle fails.

memorymappedfile^ mmf = nullptr; try { mmf = memorymappedfile::createnew("testmap", 10000, memorymappedfileaccess::readwrite); } catch (object^ ex) {     // show error     return; } safememorymappedfilehandle^ safehandle = mmf->safememorymappedfilehandle; bool success = false; safehandle->dangerousaddref(success); if (!success) {     // show error     return; } intptr handle = safehandle->dangerousgethandle(); if (safehandle->isinvalid) {     // show error     return; } pin_ptr<const wchar_t> wchstr = ptrtostringchars(message); if (!put((intptr_t)handle, const_cast<wchar_t*>(wchstr))) {     // show error     return; } safehandle->dangerousrelease(); 

and "put" function.

bool put(intptr_t h, wchar_t* message) {     int fd = _open_osfhandle(h, 0);     if (fd < 1)         return false;     file * fp = _wfdopen(fd, l"w");     fputws(message, fp);     return true; } 

the memorymappedfile::safememorymappedfilehandle property documentation says need security permission used following in few places.

[securitypermissionattribute(securityaction::linkdemand, unmanagedcode = true)] 

given memorymappedfile:

memorymappedfile mmf = ...; 

get "safe" handle. store safe handle long handle in use.

safememorymappedfilehandle safehandle = mmf.safememorymappedfilehandle; 

add reference handle it's not reclaimed:

bool success = false; safehandle.dangerousaddref(ref success); if (!success)     throw new invalidoperationexception("failed addref handle."); 

get raw handle:

intptr handle = safehandle.dangerousgethandle(); 

when you're done raw handle, release safe handle:

safehandle.dangerousrelease(); 

Comments