CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Dec 2020
    Posts
    11

    Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Hello,
    I'm having a issue with checking a return value.

    My code


    Code:
    #include <windows.h>
    #include <shlobj.h> /* For IShellLink */
    
    
    const char g_szAppName[] = "Check Shortcut";
    
    	int WidthX = 800;
    	int HeightY = 600;
    
    
    
    
    LPTSTR GetShortcutTargetPath(LPCTSTR lpszShortcutPath) {
    	//MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
        HRESULT hres;
        IShellLink* psl;
    
        TCHAR szPath[MAX_PATH];
        TCHAR szDesc[MAX_PATH];
        WIN32_FIND_DATA wfd;
        WCHAR wszTemp[MAX_PATH];
        
        hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&psl);
    
        if (SUCCEEDED(hres))
        {
            IPersistFile* ppf;
            psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
    
            MultiByteToWideChar(CP_ACP, 0, lpszShortcutPath, -1, wszTemp, MAX_PATH);
            
            hres = ppf->Load(wszTemp, STGM_READ);
            if (SUCCEEDED(hres))
            {
                hres = psl->Resolve(NULL, SLR_UPDATE);
                if (SUCCEEDED(hres))
                {
                    hres = psl->GetPath(szPath, MAX_PATH, &wfd, SLGP_RAWPATH);
                    if (FAILED(hres))
                        return szPath;
                    MessageBox(NULL, TEXT(szPath), TEXT("Shortcut Path"), MB_OK);
                }
            }
        }
        
        return szPath;
    }
    
    
    
    
     
     
    /* This is where all the input to the window goes to */
    LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {
    		switch(Message)
    			{
    				case WM_CREATE:
    					{
    						char SendToLink[MAX_PATH] = {'\0'};
    						strcat(SendToLink, getenv("APPDATA"));
    						strcat(SendToLink, "\\Microsoft\\Windows\\SendTo\\");
    						strcat(SendToLink, g_szAppName);
    						strcat(SendToLink, ".lnk");
    						
    						char AppPathName[MAX_PATH];
    						GetModuleFileName(NULL, AppPathName, MAX_PATH);
    						
    						
    						MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
    						LPCSTR TargetPath = GetShortcutTargetPath(SendToLink);
    ISSUE HERE....
    LPCSTR result = lstrcmp(TargetPath, AppPathName);
    if (result==0)
    {
    MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }					
    						
    						break;
    					}
    
    
    
    		case WM_CLOSE:
    			{
    				DestroyWindow(hwnd);
    				break;
    			}
    
    		
    		/* Upon destruction, tell the main thread to stop */
    		case WM_DESTROY: {
    			PostQuitMessage(0);
    			break;
    		}
    		
    		/* All other messages (a lot of them) are processed using default procedures */
    		default:
    			return DefWindowProc(hwnd, Message, wParam, lParam);
    	}
    	return 0;
    }
    
    /* The 'main' function of Win32 GUI programs: this is where execution starts */
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    	WNDCLASSEX wc; /* A properties struct of our window */
    	HWND hwnd; /* A 'HANDLE', hence the H, or a pointer to our window */
    	MSG msg; /* A temporary location for all messages */
    	
    
    
    	/* zero out the struct and set the stuff we want to modify */
    	memset(&wc,0,sizeof(wc));
    	wc.cbSize		 = sizeof(WNDCLASSEX);
    	wc.lpfnWndProc	 = WndProc; /* This is where we will send messages to */
    	wc.hInstance	 = hInstance;
    	wc.hCursor		 = LoadCursor(NULL, IDC_ARROW);
    	
    	/* White, COLOR_WINDOW is just a #define for a system color, try Ctrl+Clicking it */
    	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+0);
    	wc.lpszClassName = "WindowClass";
    	wc.hIcon		 = LoadIcon(NULL, IDI_APPLICATION); /* Load a standard icon */
    	wc.hIconSm		 = LoadIcon(NULL, IDI_APPLICATION); /* use the name "A" to use the project icon */
    
    	if(!RegisterClassEx(&wc)) {
    		MessageBox(NULL, "Window Registration Failed!","Error!",MB_ICONEXCLAMATION|MB_OK);
    		return 0;
    	}
    
    //	hwnd = CreateWindowEx(WS_EX_TOPMOST,"WindowClass","MyTitle",WS_SYSMENU|WS_VISIBLE,
    	hwnd = CreateWindowEx(WS_EX_TOPMOST,"WindowClass",g_szAppName,WS_SYSMENU|WS_MINIMIZEBOX,
    		GetSystemMetrics(SM_CXSCREEN) / 2 - WidthX / 2, /* x */
    		GetSystemMetrics(SM_CYSCREEN) / 2 - HeightY / 2, /* y */
    		WidthX, /* width */
    		HeightY, /* height */
    		NULL,NULL,hInstance,NULL);
    
    	if(hwnd == NULL) {
    		MessageBox(NULL, "Window Creation Failed!","Error!",MB_ICONEXCLAMATION|MB_OK);
    		return 0;
    	}
    
            
            
            
            ShowWindow(hwnd, nCmdShow);
            
    	/*
    		This is the heart of our program where all input is processed and 
    		sent to WndProc. Note that GetMessage blocks code flow until it receives something, so
    		this loop will not produce unreasonably high CPU usage
    	*/
    	while(GetMessage(&msg, NULL, 0, 0) > 0) { /* If no error is received... */
    		TranslateMessage(&msg); /* Translate key codes to chars if present */
    		DispatchMessage(&msg); /* Send it to WndProc */    
    	}
    	return msg.wParam;
    }

    IDE : Dev C++
    Thanks

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Quote Originally Posted by NewPlaza View Post
    Hello,
    I'm having a issue with checking a return value.

    My code


    Code:
    ...
    ISSUE HERE....
    LPCSTR result = lstrcmp(TargetPath, AppPathName);
    if (result==0)
    {
    MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }					
    ...

    IDE : Dev C++
    Thanks
    Well, according to Docs lstrcmp returns an integer value. So why are you trying to assign it to the LPCSTR ?
    It should be
    Code:
    int result = lstrcmp(TargetPath, AppPathName);
    if (result==0)
    {
       MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }
    Victor Nijegorodov

  3. #3
    Join Date
    Dec 2020
    Posts
    11

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    LOL! That worked! Thanks.

    Here is something odd.

    This code works (displays two message boxes, as expected).
    Code:
    MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
    LPCSTR TargetPath = GetShortcutTargetPath(SendToLink);
    int result = lstrcmp(TargetPath, AppPathName);
    if (result==0)
    {
    MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }

    But this code does not (displays no message boxes, should be one msgbox).
    Code:
    //MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
    LPCSTR TargetPath = GetShortcutTargetPath(SendToLink);
    int result = lstrcmp(TargetPath, AppPathName);
    if (result==0)
    {
    MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }
    The SendTo target does still match but it will not display Shortcut Target Path Matches msgbox.

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Quote Originally Posted by NewPlaza View Post
    ...
    But this code does not (displays no message boxes, should be one msgbox).
    Code:
    //MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
    LPCSTR TargetPath = GetShortcutTargetPath(SendToLink);
    int result = lstrcmp(TargetPath, AppPathName);
    if (result==0)
    {
         MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }
    The problem is you return from the GetShortcutTargetPath a pointer to the local char buffer (TCHAR szPath[MAX_PATH]) that goes out of scope right after this function return.
    Sometimes (very rarely) it looks like it works, but in common, unfortunately it does not.

    One of the possible solutions is: you allocate a char array/buffer with the size enough to get the "target path" and pass its pointer as an additional parameter to the GetShortcutTargetPath which then filled it with the value you need:
    Code:
    HRESULT GetShortcutTargetPath(LPCTSTR lpszShortcutPath, LPTSTR destination) 
    {
        HRESULT hres;
        IShellLink* psl;
    
    //    TCHAR szPath[MAX_PATH];
        ...
        {
            {
                hres = psl->Resolve(NULL, SLR_UPDATE);
                if (SUCCEEDED(hres))
                {
                    hres = psl->GetPath(destination, MAX_PATH, &wfd, SLGP_RAWPATH);
                    if (FAILED(hres))
                        return hres;
                    MessageBox(NULL, TEXT(destination), TEXT("Shortcut Path"), MB_OK);
                }
            }
        }
        
        return S_OK;
    }
    ...
    case WM_CREATE:
    					{
    						...
    						char TargetPath [MAX_PATH] = {0};
    						
    						MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
    						HRESULT result  = GetShortcutTargetPath(SendToLink, TargetPath);
    						...
    Victor Nijegorodov

  5. #5
    Join Date
    Dec 2020
    Posts
    11

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Thank you so much for helping me. I'm still trying to understand your code. You have char TargetPath [MAX_PATH] = {0};..
    But my "target path" would be where my application resides and I use this code.
    Code:
    char AppPathName[MAX_PATH];
    GetModuleFileName(NULL, AppPathName, MAX_PATH);
    but HRESULT result = GetShortcutTargetPath(SendToLink, TargetPath); or HRESULT result = GetShortcutTargetPath(SendToLink, AppPathName); always returns true(displaying msgbox, Shortcut Target Path Matches) even when the sendto shortcut doesn't even exist.

    Thank you.

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    If GetShortcutTargetPath() is only used once, then within that function make szPath static. Also set szpath[0] = 0 at the start of the function so if it fails the value is a null.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Dec 2020
    Posts
    11

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Thank you for the reply... No, that function will be used many times throughout my program testing various shortcuts. It's clear to me I simply don't understand the fundamental principles of function calling within C/C++. While I appreciate your(and VictorN's) help I not sure if you signed up for full time hand holding, lol!
    Can anyone recommend a C++ book that doesn't just talk about cin this, cout that....

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    The issue's not really function calling, it's understanding variable scope. A variable is only valid within the block it's declared. Outside of that block it's undefined.

    szpath is defined with the function, so it's only valid within that function. Returning its memory address doesn't get around the issue that once the function ends, szpath is invalid and so the returned memory address is invalid. Simply, why not pass szpath as a function parameter to GetShortcutTargetPath().

    Consider (not tried):

    Code:
    bool GetShortcutTargetPath(LPCTSTR lpszShortcutPath, TCHAR szPath[MAX_PATH]) {
    	szPath[0] = 0;
    
    	IShellLink* psl = nullptr;
    	WCHAR wszTemp[MAX_PATH] {};
    
    	HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&psl);
    
    	if (SUCCEEDED(hres))
    	{
    		IPersistFile* ppf;
    		psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
    
    		MultiByteToWideChar(CP_ACP, 0, lpszShortcutPath, -1, wszTemp, MAX_PATH);
    
    		hres = ppf->Load(wszTemp, STGM_READ);
    		if (SUCCEEDED(hres))
    		{
    			hres = psl->Resolve(NULL, SLR_UPDATE);
    			if (SUCCEEDED(hres))
    			{
    				WIN32_FIND_DATA wfd;
    
    				hres = psl->GetPath(szPath, MAX_PATH, &wfd, SLGP_RAWPATH);
    				if (FAILED(hres))
    					return false;
    
    				MessageBox(NULL, TEXT(szPath), TEXT("Shortcut Path"), MB_OK);
    			}
    		}
    	}
    
    	return true;
    }
    and then used something like:

    Code:
    // MessageBox(NULL, TEXT("Checking SendTo path"), TEXT("Shortcut Path"), MB_OK);
    TCHAR szPath[MAX_PATH] {};
    
    const bool res = GetShortcutTargetPath(SendToLink, szPath);
    const int result = lstrcmp(szPath, AppPathName);
    
    if (res && result == 0)
    {
    	MessageBox(NULL, TEXT(TargetPath), TEXT("Shortcut Target Path Matches."), MB_OK);
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Can anyone recommend a C++ book
    What's your level of knowledge of C++?

    The two general C++ books I'd suggest are:

    Beginning C++20 by Ivor Horton
    Professional C++ by by Marc Gregoire (5th Edition coming 7 Jan 2021)

    Also learncpp.com web site.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  10. #10
    Join Date
    Dec 2020
    Posts
    11

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Quote Originally Posted by 2kaud View Post
    Returning its memory address doesn't get around the issue that once the function ends, szpath is invalid and so the returned memory address is invalid.
    Wow! I did not know that.. Alot of stuff is now making more sense.

    What's your level of knowledge of C++?
    Far worst than I first thought!!

    And thank you for the code snippet. I will play with it later tonight.

  11. #11
    Join Date
    Dec 2020
    Posts
    11

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Fantastic! Thanks for the code. I had to make a small change.
    Code:
    if (res && result == 0)
    to
    Code:
    if (result == 0)
    and I had to add CoInitialize(NULL);
    Apparently, it's needed to initialize the COM library.
    Also, I gonna do more reading on shell links because I might be missing ppf->/psl->Release();.
    I'm assuming this may pose a memory leak issue or something.
    But nonetheless, it works exactly as expected. Thanks.

    Time for light e-book reading, lol.

  12. #12
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Quote Originally Posted by NewPlaza View Post
    Quote Originally Posted by 2kaud
    Returning its memory address doesn't get around the issue that once the function ends, szpath is invalid and so the returned memory address is invalid.
    Wow! I did not know that.. Alot of stuff is now making more sense.
    Didn't you read the post#4?
    Victor Nijegorodov

  13. #13
    Join Date
    Dec 2020
    Posts
    11

    Re: Test return value - invalid conversion from 'int' to 'LPCSTR {aka const char*}'

    Quote Originally Posted by VictorN View Post
    Didn't you read the post#4?
    lol.. Yes I did but I guess I really didn't comprehend it(I thought I did though).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured