biprinea biprinea - 8 months ago 34
C Question

How to run a dll as a service?

I know how to write a dll and how to write a service and how to run a dll with

, but now I want to write a dll that install as a service in windows

I don't know if that's possible or which function in dll should be exported?

How can I install and run a dll as a service?


There's actually no inherent reason why you can't use rundll32.exe as the host executable, though use of rundll32 isn't recommended. (To expand on that: I gather you're trying to build a DLL service as an academic exercise, which is fine. In production, you should of course use an EXE, as you've already done.)

Your main function should have this signature:

void CALLBACK MyServiceEntry(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)

and should call StartServiceCtrlDispatcher, in the same way as the main() or WinMain() function in a conventional service.

You would then install the service to use the following command line:

rundll32 MyService.dll,MyServiceEntry

For an academic exercise, it would also be acceptable to use svchost.exe as described in Remy's answer, but it is even more important not to use that in a production context: the use of rundll32 by third parties is supported but not recommended; the use of svchost by third parties is explicitly unsupported.