Home > Software engineering >  Creating a Service in vs2019
Creating a Service in vs2019

Time:10-23

I wanted to create a service in VS2019, but it hasn't a template for it. So I created an empty project and then I try to write a service from ground up. I written the following main function.

#define SERVICE_NAME  _T("My Sample Service")

int _tmain(int argc, TCHAR* argv[])
{
    OutputDebugString(_T("My Sample Service: Main: Entry"));

    SERVICE_TABLE_ENTRY ServiceTable[] =
    {
        {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
        {NULL, NULL}
    };

    if (StartServiceCtrlDispatcher(ServiceTable) == FALSE)
    {
        OutputDebugString(_T("My Sample Service: Main: StartServiceCtrlDispatcher returned error"));
        return GetLastError();
    }

    OutputDebugString(_T("My Sample Service: Main: Exit"));
    return 0;
}

But It says, you can't initialize a LPWSTR with a const wchar_t. This error is belong to the following line:

SERVICE_TABLE_ENTRY ServiceTable[] =
        {
            {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
            {NULL, NULL}
        };

But when I was watching video tutorial, the authro exactly written the above code but in vs 2019 I can't write such things. What should I do now?

CodePudding user response:

This has been asked a lot of times before, but apparently I can't find a good duplicate to link here.

The issue is that the structure is defined as follows:

typedef struct _SERVICE_TABLE_ENTRYW {
  LPWSTR                   lpServiceName;
  LPSERVICE_MAIN_FUNCTIONW lpServiceProc;
} SERVICE_TABLE_ENTRYW, *LPSERVICE_TABLE_ENTRYW;

LPWSTR is wchar_t*. String literal L"..." can be assigned to const wchar_t* pointer, but not wchar_t* pointer.

Previously the Visual C compiler accepted such code. Now it will accept it with /permissive, but will reject with /permissive-.

/permissive is the default option for the compiler, but /permissive- is set by default in Console Application project template. Generally, you shouldn't want to set /permissive for new code, it is more like an aid to port old code.

So, to fix compilation, you can:

  • use /permissive
  • cast away constness by const_cast or C-style cast
  • use non-constant variable, like wchar_t ServiceName[] = L"My Sample Service"

The last option is generally safest, as it makes no assumptions not defined by type system. However, the others are likely to be good enough, since this appears to be a widespread code sample for a service, and it is unlikely that it ever stops working.

  • Related