简体   繁体   中英

Need help passing some LPCTSTR's to a function in C++

I'm very new to C++ and have a question that is probably obvious. I am able to use the MSDN example to install a service (http://msdn.microsoft.com/en-us/library/ms682450%28v=VS.85%29.aspx) if I have it in a stand alone program.

I'm trying to add this as a function inside another project and am having trouble passing the LPCTSTR strings it needs for the name, binary path etc.

So far I have tried:

int Install(LPCTSTR serviceName, LPCTSTR serviceDisplayName, LPCTSTR servicePath);

I know this is wrong, but am having a hard time finding out what I should use exactly. Even a link pointing to an explanation is fine. Thanks!

LPCTSTR is

long pointer to const text string

Depending on whether you are targeting a UNICODE/MBCS/ANSI build you'd need

  • const char* (ANSI/MBCS)
  • const wchar_t* (UNICODE)

(from memory)

Here's an example that support Unicode or non-Unicode builds. Note you want both UNICODE and _UNICODE defined to work properly in a Unicode build. Wrap all text strings in the _T macro.

#include <windows.h>  /* defines LPCTSTR and needs UNICODE defined for wide build. */
#include <stdio.h>
#include <tchar.h>    /* defines _T, _tprintf, _tmain, etc. and needs _UNICODE defined for wide build. */

int Install(LPCTSTR serviceName, LPCTSTR serviceDisplayName, LPCTSTR servicePath)
{
    _tprintf(_T("%s %s %s\n"),serviceName,serviceDisplayName,servicePath);
    return 0;
}

int _tmain(int argc, LPTSTR argv[])
{
    int i;
    LPCTSTR serviceName = _T("serviceName");
    LPCTSTR serviceDisplayName = _T("serviceDisplayName");
    LPCTSTR servicePath = _T("servicePath");

    for(i = 0; i < argc; i++)
        _tprintf(_T("argv[%d] = %s\n"),i,argv[i]);

    Install(serviceName,serviceDisplayName,servicePath);

    return 0;
}

If you already have the LPCTSTR s, then you simply call the function as:

int result = Install(serviceName, serviceDisplayName, servicePath);

LPCTSTR is a long pointer to a const TCHAR string, so it's usually const char * or const wchar_t * , depending on your unicode settings. Due to that, you can use a lot of the usual methods for working with C strings, as well as any Microsoft provides (I believe the MFC has some string classes/functions).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM