需要帮助将一些 LPCTSTR 传递给 C++ 中的函数

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

本文关键字:C++ 函数 LPCTSTR 帮助      更新时间:2023-10-16

我对C++很陌生,有一个问题可能很明显。我可以使用MSDN示例来安装服务(http://msdn.microsoft.com/en-us/library/ms682450%28v=VS.85%29.aspx)如果我把它放在一个单独的项目中。

我正试图将其添加为另一个项目中的函数,并且在传递名称、二进制路径等所需的LPCTSTR字符串时遇到了问题。

到目前为止,我已经尝试过:

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

我知道这是错误的,但我很难弄清楚我到底应该用什么。即使是指向解释的链接也可以。谢谢

LPCTSTR是

long pointer to const text string

根据您是否针对UNICODE/MBCS/ANSI构建,您需要

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

(来自内存(

这里有一个支持Unicode或非Unicode构建的示例。请注意,您希望定义的UNICODE_UNICODE都能在Unicode构建中正常工作。换行_T宏中的所有文本字符串。

#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 %sn"),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] = %sn"),i,argv[i]);
    Install(serviceName,serviceDisplayName,servicePath);
    return 0;
}

如果您已经有了LPCTSTR s,那么您只需将函数调用为:

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

LPCTSTR是一个指向常量TCHAR字符串的长指针,因此它通常是const char *const wchar_t *,具体取决于您的unicode设置。因此,您可以使用许多常用的方法来处理C字符串,以及Microsoft提供的任何方法(我相信MFC有一些字符串类/函数(。