DLLs mit C# und Powershell – I

Hier eine kurze Anleitung, wie man mit C# eigene DLLs erstellt und diese von Powershell aus benutzt. Ich nutze die kostenlose Version von Visual Studio, Visual C# Express 2008. Als umzusetzender Algorithmus kommt Levenshtein zum Einsatz, über den ich öfter schon geschrieben habe, die Funktion stammt aus der englischen Wikipedia.

In VS lege ich ein neues Projekt vom Typ Klassenbibliothek an, als Namespace wähle ich „de.uweziegenhagen“. Das Projekt habe ich unter dem Namen „simpledll“ abgespeichert, die „Class1“ Datei in TextCompare.cs umbenannt. Hier der Quelltext für die statische Klasse, wichtig ist, dass die Levenshtein Funktion „public static“ ist, nicht „private“ wie in der Wikiedia.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace de.uweziegenhagen
{
    public static class TextCompare
    {
 
        public static Int32 levenshtein(String a, String b)
        { // http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#C.23
 
            if (string.IsNullOrEmpty(a))
            {
                if (!string.IsNullOrEmpty(b))
                {
                    return b.Length;
                }
                return 0;
            }
 
            if (string.IsNullOrEmpty(b))
            {
                if (!string.IsNullOrEmpty(a))
                {
                    return a.Length;
                }
                return 0;
            }
 
            Int32 cost;
            Int32[,] d = new int[a.Length + 1, b.Length + 1];
            Int32 min1;
            Int32 min2;
            Int32 min3;
 
            for (Int32 i = 0; i <= d.GetUpperBound(0); i += 1)
            {
                d[i, 0] = i;
            }
 
            for (Int32 i = 0; i <= d.GetUpperBound(1); i += 1)
            {
                d[0, i] = i;
            }
 
            for (Int32 i = 1; i <= d.GetUpperBound(0); i += 1)
            {
                for (Int32 j = 1; j <= d.GetUpperBound(1); j += 1)
                {
                    cost = Convert.ToInt32(!(a[i - 1] == b[j - 1]));
 
                    min1 = d[i - 1, j] + 1;
                    min2 = d[i, j - 1] + 1;
                    min3 = d[i - 1, j - 1] + cost;
                    d[i, j] = Math.Min(Math.Min(min1, min2), min3);
                }
            }
 
            return d[d.GetUpperBound(0), d.GetUpperBound(1)];
 
        }
    }
}

Das Übersetzen der DLL sollte problemlos funktionieren, die fertige DLL sollte im PRojektverzeichnis unter /bin/release liegen.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website