C# | Access Violation When Using Shared Memory From C/C++

When using dll made in C/C++ with the API below, a program in C# occurs ‘Access Violation’.

CreateFileMapping
OpenFileMapping
MapViewOfFile

 
The below doesn’t work. So message passing with named pipe is in the air instead of shared memory.

 
 
———————————————————————-
 
It can be resolved by using another API in C#.

 

[Resolution]
Apply this

                for (int i = 0; i < size; i++)
                    rawDataArray[i] = Marshal.ReadByte(rawData + i);

Instead of the below.

                //Marshal.Copy(rawData, rawDataArray, 0, size);

 

[Shared Memory Example]

	SECURITY_ATTRIBUTES SecAttr, *pSec = 0;
	SECURITY_DESCRIPTOR SecDesc;

	if (InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION) &&
		SetSecurityDescriptorDacl(&SecDesc, TRUE, (PACL)0, FALSE))
	{
		SecAttr.nLength = sizeof(SecAttr);
		SecAttr.lpSecurityDescriptor = &SecDesc;
		SecAttr.bInheritHandle = TRUE;
		pSec = &SecAttr;
	}

	live_h_map_file = CreateFileMapping(
		INVALID_HANDLE_VALUE,    // use paging file
		pSec,                    // default security
		PAGE_READWRITE,          // read/write access
		0,                       // maximum object size (high-order DWORD)
		sizeof(LIVE_DATA),                // maximum object size (low-order DWORD)
		LIVE_SHARED_MAP_OBJ_NAME);                 // name of mapping object

	if(!live_h_map_file)
	{
		cs_log("Could not set shared memory for live capture variable.\n");
		return -1;
	}

*h_map_file = OpenFileMapping(
		FILE_MAP_WRITE, //FILE_MAP_ALL_ACCESS,   // read/write access
		FALSE,                 // do not inherit the name
		LIVE_SHARED_MAP_OBJ_NAME);                 // name of mapping object

	if(!(*h_map_file)) {
		cs_log("Could not get shared memory for live catpure.\n");
		return -1;
	}
	*live_data = (LIVE_DATA *) MapViewOfFile(*h_map_file,   // handle to map object
		FILE_MAP_WRITE, // FILE_MAP_ALL_ACCESS, // read&write permission
		0,
		0,
		sizeof(LIVE_DATA));

	if(!(*live_data)) {
		cs_log("Could not set shared live catpture.\n");
		CloseHandle(*h_map_file);
		return -2;
	}
Advertisements
C# | Access Violation When Using Shared Memory From C/C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s