Implement IDispose properly

pull/2/head
Francesco Bertolaccini 2016-02-09 11:21:08 +01:00
parent d391a6973c
commit 6ce6af5fa0
2 changed files with 50 additions and 5 deletions

View File

@ -99,6 +99,7 @@ namespace SharpPhysFS
}
class Interop
: IDisposable
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FnGetLinkedVersion(ref Version v);
@ -200,6 +201,11 @@ namespace SharpPhysFS
: this($"{libname}.dll", $"{libname}.dylib", $"{libname}.so")
{ }
Func<string, IntPtr> loadLibrary;
Func<IntPtr, string, IntPtr> loadSymbol;
Func<IntPtr, bool> freeLibrary;
IntPtr library;
public Interop(string winlib, string maclib, string unixlib)
{
/* This method is used to dynamically load the physfs
@ -211,28 +217,27 @@ namespace SharpPhysFS
* pointers from the loaded library
*/
Func<string, IntPtr> loadLibrary;
Func<IntPtr, string, IntPtr> loadSymbol;
string libraryName;
IntPtr library;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
loadLibrary = DynamicLoader.LoadLibrary;
loadSymbol = DynamicLoader.GetProcAddress;
freeLibrary = DynamicLoader.FreeLibrary;
libraryName = winlib;
}
else if(Environment.OSVersion.Platform == PlatformID.MacOSX)
{
loadLibrary = n => DynamicLoader.osx_dlopen(n, 1);
loadSymbol = DynamicLoader.osx_dlsym;
freeLibrary = DynamicLoader.osx_dlclose;
libraryName = maclib;
}
else
{
loadLibrary = n => DynamicLoader.unix_dlopen(n, 1);
loadSymbol = DynamicLoader.unix_dlsym;
freeLibrary = DynamicLoader.unix_dlclose;
libraryName = unixlib;
}
@ -252,5 +257,29 @@ namespace SharpPhysFS
field.SetValue(this, del);
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
/*if (disposing)
{
// TODO: dispose managed state (managed objects).
}*/
freeLibrary(library);
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}

View File

@ -693,9 +693,25 @@ namespace SharpPhysFS
return new PhysFSStream(this, handle, false);
}
public void Dispose()
bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
Deinit();
interop.Dispose();
}
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}