sigvardsen
sigvardsen

Reputation: 1531

CreateFileMapping() name

Im creating a DLL that shares memory between different applications.

The code that creates the shared memory looks like this:

#define NAME_SIZE 4
HANDLE hSharedFile;

create(char[NAME_SIZE] name)
{
    hSharedFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, (LPCSTR)name);
    (...) //Other stuff that maps the view of the file etc.
}

It does not work. However if I replace name with a string it works:

SharedFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, (LPCSTR)"MY_TEST_NAME");

How can I get this to work with the char array?

I have a java background where you would just use string all the time, what is a LPCSTR? And does this relate to whether my MS VC++ project is using Unicode or Multi-Byte character set

Upvotes: 0

Views: 1810

Answers (2)

Elalfer
Elalfer

Reputation: 5338

I suppose you should increase NAME_SIZE value.

Do not forget that array must be at least number of chars + 1 to hold \0 char at the end, which shows the end of the line.

LPCSTR is a pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters and defined as follows:

LPCSTR defined as typedef __nullterminated CONST CHAR *LPCSTR; 

For example even if you have "Hello world" constant and it has 11 characters it will take 12 bytes in the memory.

If you are passing a string constant as an array you must add '\0' to the end like {'T','E','S','T', '\0'}

Upvotes: 2

casablanca
casablanca

Reputation: 70701

If you look at the documentation, you'll find that most Win32 functions take an LPCTSTR, which represents a string of TCHAR. Depending on whether you use Unicode (the default) or ANSI, TCHAR will expand to either wchar_t or char. Also, LPCWSTR and LPCSTR explicitly represent Unicode and ANSI strings respectively.

When you're developing for Win32, in most cases, it's best to follow suit and use LPCTSTR wherever you need strings, instead of explicit char arrays/pointers. Also, use the TEXT("...") macro to create the correct kind of string literals instead of just "...".

In your case though, I doubt this is causing a problem, since both your examples use only LPCSTR. You have also defined NAME_SIZE to be 4, could it be that your array is too small to hold the string you want?

Upvotes: 1

Related Questions