packages feed

Hs2lib-0.4.8: Includes/FFI/SafeString.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WinDll.Utils
{
    /// <summary>
    /// Just a way to make the constructor also free unmanaged pointers.
    /// This saves us from having to make repeated calls ourselves
    /// </summary>
    public unsafe class SafeString
    {
        /// <summary>
        /// Return a managed string from the char* pointer 
        /// and then free the pointer
        /// </summary>
        /// <param name="pointer">The unsafe string pointer</param>
        /// <returns>The char* as a managed string</returns>
        public unsafe static string Create(char* pointer)
        {
            string msg = new string(pointer);
            FFI.free(pointer);
            pointer = null;
            return msg;
        }

        /// <summary>
        /// Return a managed string from the char* pointer 
        /// and then free the pointer
        /// </summary>
        /// <param name="pointer">The unsafe string pointer</param>
        /// <returns>The void* as a managed string</returns>
        public unsafe static string Create(void* pointer)
        {
            if (pointer == null) return "";
            return Create((char*)pointer);
        }

        /// <summary>
        /// The representation used most often for marshalling array is to return
        /// for every array a tuple. The first element of the tuple is the size of
        /// the array and the second element the array itself.
        /// </summary>
        /// <param name="pointer">The unsafe string array pointer</param>
        /// <returns>string array</returns>
        public static unsafe string[] CreateArray(Tuples.Tuple2* values)
        {
            int length = (int)values->tuple2_var1;
            string[] result = new string[length];
            char** value = (char**)values->tuple2_var2;

            for (int i = 0; i < length; i++)
            {
                result[i] = SafeString.Create(value[i]);
            }

            FFI.free(values);

            return result;
        }
    }
}