Allocate Static Shared Memory using MapViewOfFile

621 views Asked by At

How can I allocated shared memory to a static buffer like the following but using CreateFileMapping and MapViewOfFile.

#pragma data_seg(".ABC")
__declspec (dllexport) char buffer[10000]  = {0};
#pragma data_seg()
#pragma comment(linker, "-section:.ABC,rws")

The goal is to create a static shared buffer that is shared between C++ and FORTRAN applications, like it's done when using data_seg. When creating a dynamic allocated buffer, FORTRAN gets tricky because you need to de-reference the pointer, which is also doable, but it's not what I want.

1

There are 1 answers

5
Remy Lebeau On

The equivalent Win32 API calls would look like this:

SECURITY_DESCRIPTOR sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);

SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE;

HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0, 10000, TEXT("ABC")); 
if (!hMapping) ... // error handling

char *buffer = (char*) MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 10000);
if (!buffer) ... // error handling

// use buffer as needed... 

UnmapViewOfFile(buffer);
CloseHandle(hMapping);

Both apps would have to call CreateFileMapping() with the same lpName value to gain access to the same mapping object in the system kernel. Whichever app calls CreateFileMapping() first will create the object, and the second app will get a handle to the existing object. Then, MapViewOfFile() maps memory access within the calling process to that object. In this way, both apps are using shared memory with each other. When one app writes data into the object, the other app will see it.