views:

96

answers:

3

I have one application which reads user default locale in Windows Vista and above. When i tried calling the API for getting User default Locale API is crashing. Below is the code, It will be helpfull if any points the reason

#include <iostream>
#include <WinNls.h> 
#include <Windows.h>

int main()
{
    LPWSTR lpLocaleName=NULL;
    cout << "Calling GetUserDefaultLocaleName";
    int ret = GetUserDefaultLocaleName(lpLocaleName, LOCALE_NAME_MAX_LENGTH);
    cout << lpLocaleName<<endl;
}
+1  A: 

I believe you need to initialise lpLocaleName to an empty string of 256 chars (for example) then pass the length (256) where you have LOCALE_NAME_MAX_LENGTH

Nanook
No, I had tried this before and this is not helped!
Santhosha
+3  A: 

You need to have lpLocaleName initialized to a buffer prior to calling the API. As a general consensus, if an API has a LPWSTR data type parameter, call malloc or new on it first, to the desired length, in this case, LOCALE_NAME_MAX_LENGTH. Setting it to NULL and passing it to the API function is a guaranteed way to crash!

Hope this helps, Best regards, Tom.

tommieb75
Thanks Tom,This resolved my crash issue.. Thanks a lot..
Santhosha
+1  A: 

In addition to the previous answers, you should also be aware that you can't print a wide string with cout; instead, you should use wcout. So:

#include <iostream>
#include <WinNls.h> 
#include <Windows.h>

#define ARRSIZE(arr) (sizeof(arr)/sizeof(*(arr)))

using namespace std;

int main()
{
    WCHAR_T localeName[LOCALE_NAME_MAX_LENGTH]={0};
    cout<<"Calling GetUserDefaultLocaleName";
    int ret = GetUserDefaultLocaleName(localeName,ARRSIZE(localeName));
    if(ret==0)
        cout<<"Cannot retrieve the default locale name."<<endl;
    else
        wcout<<localeName<<endl;
    return 0;
}
Matteo Italia
Yes.. Now i can print the OS locale.. Thanks a lot...:)
Santhosha
This API is returning locale name like "en-US" etc.. Can i get locale ID from this locale name??
Santhosha