#include "Stdafx.h"

#pragma once
#include "lkfxdok.h"
#include "LKFMemoryDelegate.h"

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

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

namespace lkfxdok {
	namespace c {
		LKFMemoryDelegate::LKFMemoryDelegate(LKFMemoryDelegateFunction^ managedDelegateFunction, int delegateFlags) {
			this->_delegateFlags = delegateFlags;
			this->_managedDelegateFunction = managedDelegateFunction;
			this->_delegateFunction = gcnew LKFUnmanagedMemoryDelegateFunction(this, &LKFMemoryDelegate::memoryDelegate);

		}

		LKFMemoryDelegate::~LKFMemoryDelegate() {
		}

		void LKFMemoryDelegate::memoryDelegate(void* context, const char *op, const char *key, long long ptr, long elem, long siz) {
			
			String^ gcOp = gcnew String(op);
			String^ gcKey = gcnew String(key);
		    _managedDelegateFunction(gcOp, gcKey, ptr, elem, siz);
		}

		void LKFMemoryDelegate::Assign() {
			_unmanagedFileDelegate = Marshal::GetFunctionPointerForDelegate(_delegateFunction);
			::lkf_setMemoryTraceDelegate((LKFMEMORY_DELEGATE)(void*)_unmanagedFileDelegate, _delegateFlags);
		}

		void LKFMemoryDelegate::Deassign() {
			::lkf_setMemoryTraceDelegate(nullptr, 0);
		}
	}
}