
#include "stdafx.h"
#include "LKFSemaphoreHandler.h"

extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lkf5defs.h"
}

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

namespace lkfxdok {
	namespace c {

		LKFSemaphoreHandler::LKFSemaphoreHandler() {
			allocDelegate = gcnew LKFAllocSemaphoreDelegate (this, &LKFSemaphoreHandler::allocSemaphore);
			enterDelegate = gcnew LKFSemaphoreDelegate(this, &LKFSemaphoreHandler::enterSemaphore);
			leaveDelegate = gcnew LKFSemaphoreDelegate(this, &LKFSemaphoreHandler::leaveSemaphore);
			deleteDelegate = gcnew LKFSemaphoreDelegate(this, &LKFSemaphoreHandler::deleteSemaphore);

			marshaledAllocCallback = Marshal::GetFunctionPointerForDelegate(this->allocDelegate);
			marshaledEnterCallback = Marshal::GetFunctionPointerForDelegate(this->enterDelegate);
			marshaledLeaveCallback = Marshal::GetFunctionPointerForDelegate(this->leaveDelegate);
			marshaledDeleteCallback = Marshal::GetFunctionPointerForDelegate(this->deleteDelegate);

			_semaphore = gcnew System::Threading::Semaphore(1, 1);
		}

		void LKFSemaphoreHandler::assign() {
			lkf_semaphore_callbacks2((ALLOC_SEMAPHORE_CALLBACK2)(void*)marshaledAllocCallback, (SEMAPHORE_CALLBACK2)(void*)marshaledEnterCallback, (SEMAPHORE_CALLBACK2)(void*)marshaledLeaveCallback, (SEMAPHORE_CALLBACK2)(void*)marshaledDeleteCallback);

		}

		long LKFSemaphoreHandler::allocSemaphore() {
			return 1;
		}

		void LKFSemaphoreHandler::enterSemaphore(long sem) {
			_semaphore->WaitOne();
		}

		void LKFSemaphoreHandler::leaveSemaphore(long sem) {
			_semaphore->Release();
		}

		void LKFSemaphoreHandler::deleteSemaphore(long sem) {

		}
	}
}