0
votes

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
What is the actual question?Andre Kampling
Are we supposed to know what CreateFileMapping and MapViewOfFile are?Jonathan Mee
@JonathanMee: Functions of the WinAPI: CreateFileMapping and MapViewOfFile. OP: What is your goal, to share with what? Could you please provide more information?Andre Kampling
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.user3716892
@user3716892 what makes you think MapViewOfFile will be any better? You will still have a pointer to dynamically allocated memory (within the system paging file). It won't be static.Remy Lebeau

1 Answers

1
votes

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.