I am working on a C++ project that has different components. We need to start the application as a windows service. The project is unmanaged C++ code. I wrote a C# windows service, and a C-style dll that will have a function to start the different components, and another to stop them. The dll has two files, a header and a .cpp file: RTSS.h:
namespace PFDS
{
extern "C" __declspec(dllexport) int runRTS(char*);
}
RTSS.cpp:
using namespace PFDS;
/* ... includes and declarations */
extern "C" __declspec(dllexport) int runRTS(char* service_name)
{
g_reserved_memory = (char*) malloc(sizeof(char) * RESERVED_MEMORY_SIZE);
_set_new_handler(memory_depletion_handler);
// this function is from a C++ .lib which is included in
// the linker input for the RTSS dll project setting.
// SetUnhandledExceptionHandler("RTS");
return 0;
}
In the ServiceBase subclass of the windows service, I have the following:
[DllImport("RTSSd.dll")]
public static extern int runRTS(string serviceName);
protected override void OnStart(string[] args)
{
try
{
// the bin directory has all dependencies (dlls needed)
Environment.CurrentDirectory = "D:/work/projects/bin";
eventLog1.WriteEntry("RTSWinService: Starting " + this.ServiceName);
int result = runRTS(this.ServiceName);
eventLog1.WriteEntry("Result of invoking runRTS = " + result);
}
catch (Exception e)
{
eventLog1.WriteEntry("Exception caught: " + e.ToString());
}
}
Furthermore I have a console test application with code inside main similar to that inside OnStart. Both the application and the windows service runs with no problem when the SetUnhandledException function is commented. But when I uncomment that function, the windows console application runs ok, but the windows service outputs the following exception:
System.DllNotFoundException: Unable to load DLL 'RTSSd.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at RTSWS.RTSWinService.runRTS(String serviceName) at RTSWS.RTSWinService.OnStart(String[] args) in D:\work\project\ ...\RTSWinService.cs:line 39
I have read in some threads in different forums that the windows services start in C:\WINDOWS\System32, and it is true since initializing a DirectoryInfo and printing its full name shows so. I tried to change the default start directory with Environment.CurrentDirectory = "directory where the windows service executable and dlls are", but that didn't work. I also tried to change the Process directory, but that failed too. Other threads lead to this conclusion link text, but is it really that? Could it be something simpler? I should note that the SetUnhandledException function is written in C++, not C, and so are many other functions that I need to call. All the needed dlls are placed next to the service executable. Your feedback is much appreciated.
Thanks.