Instantiating .Net classes and methods from Windows service

  • Thread starter Thread starter its_me_here
  • Start date Start date
I

its_me_here

Guest
I am trying to access a c#.Net library from a C++ Windows service. Here is my C# library relevant code:

namespace ManagedCode
{
public class Service
{
public Service()
{

}

public void Process(int message)
{
// Do something with the input
}
}
}

I am using a separate c++ CLR project ( called MixedCode) in between the service and C# library. Here is the relevant code of the CLR layer.

using namespace ManagedCode;
using namespace System;
using namespace System::Runtime::InteropServices;

namespace MixedCode
{
CppService::CppService()
{
// Instantiate the .Net opbject
Service^ service = gcnew Service();

// Pin the .NET object, and record the address of the pinned object in m_impl
m_impl = GCHandle::ToIntPtr(GCHandle::Alloc(service)).ToPointer();
}

CppService::~CppService()
{
// Get the GCHandle associated with the pinned object based on its
// address, and free the GCHandle. At this point, the C#
// object is eligible for GC.
GCHandle handle = GCHandle::FromIntPtr(IntPtr(m_impl));
handle.Free();
}

void CppService::process(int message)
{
// Get the pinned .Net object from its memory address
GCHandle handle = GCHandle::FromIntPtr(IntPtr(m_impl));
Service^ service = safe_cast<Service^>(handle.Target);

service->Process(message);
}
}

Here is my relevant Windows service code:

#pragma comment(lib, "...path..\MixedCode.lib")

#include <iostream>
#include "../MixedCode/CppService.h"
using namespace MixedCode;


void CSampleService::OnStart(DWORD dwArgc, LPWSTR *lpszArgv)
{
// Queue the main service function for execution in a worker thread.
CThreadPool::QueueUserWorkItem(&CSampleService::ServiceWorkerThread, this);
}

void CSampleService::ServiceWorkerThread(void)
{
// Periodically check if the service is stopping.
try
{
OutputDebugString(L"#ServiceWorkerThread");
CppService service;
service.process(123);

while (!m_fStopping)
{
// Perform main service function here...

::Sleep(2000); // Simulate some lengthy operations.
}

// Signal the stopped event.
SetEvent(m_hStoppedEvent);
}
catch (...)
{
OutputDebugString(L"#ServiceWorkerThread: Exception");
}
}

When the service starts and worker thread creates the service(CLR) instance and calls the process method, the service stops with error (1053) "The service did not respond in a timely fashion". What could be wrong here? Is there anything to be done with raising the privilege in order to access the managed code since the service runs in the local account. I am able to access the managed code using the same method using a normal MFC app/console app instead of Windows service

Continue reading...
 
Back
Top