Skip to content

Instantly share code, notes, and snippets.

@tondrej
Last active April 18, 2018 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tondrej/bb88e1bce07cf6d66e0b88b5e4f59ea3 to your computer and use it in GitHub Desktop.
Save tondrej/bb88e1bce07cf6d66e0b88b5e4f59ea3 to your computer and use it in GitHub Desktop.
FastText wrapper class
public delegate bool WordCallback(string word, Single score);
class FastText : IDisposable
{
private IntPtr ft = IntPtr.Zero;
private WordCallback c = null;
private void FastTextCheck(bool result)
{
if (!result)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
if (ft != IntPtr.Zero)
{
FastTextWrapper.fasttext_release(ft);
ft = IntPtr.Zero;
}
}
public FastText() {
FastTextCheck(FastTextWrapper.fasttext_new(out ft));
}
~FastText() {
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
public bool NN2Callback(StringBuilder word, Single score, IntPtr data)
{
return c(word.ToString(), score);
}
public void NN2(IntPtr vectors, string[] positive, string[] negative, int count, WordCallback callback)
{
c = callback;
try
{
FastTextCheck(FastTextWrapper.fasttext_nn2(ft, vectors, positive, negative, count, new FastTextWrapper.FastTextNNCallback(NN2Callback), IntPtr.Zero));
}
finally
{
c = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment