using System; using System.Diagnostics; using System.Runtime.InteropServices; using LibUsbDotNet.Main; namespace MonoLibUsb { /// /// Class representing a Libusb-1.0 session session handle. /// Session handled are wrapped in a . /// /// /// The concept of individual Libusb-1.0 sessions allows for your program to use two libraries /// (or dynamically load two modules) which both independently use libusb. This will prevent interference between the /// individual libusb users - for example will not affect the other /// user of the library, and will not destroy resources that the /// other user is still using. /// Sessions are created when a new instance is created and destroyed through . /// A instance must be created before calling any other Libusb-1.0 API function. /// Session handles are equivalent to a libusb_context. /// public class MonoUsbSessionHandle:SafeContextHandle { private static Object sessionLOCK = new object(); private static MonoUsbError mLastReturnCode; private static String mLastReturnString=String.Empty; private static int mSessionCount; private static string DLL_NOT_FOUND_LINUX = "libusb-1.0 library not found. This is often an indication that libusb-1.0 was installed to '/usr/local/lib' and mono.net is not looking for it there. To resolve this, add the path '/usr/local/lib' to '/etc/ld.so.conf' and run 'ldconfig' as root. (http://www.mono-project.com/DllNotFoundException)"; private static string DLL_NOT_FOUND_WINDOWS = "libusb-1.0.dll not found. If this is a 64bit operating system, ensure that the 64bit version of libusb-1.0.dll exists in the '\\Windows\\System32' directory."; /// /// If the session handle is , gets the status code indicating the reason. /// public static MonoUsbError LastErrorCode { get { lock (sessionLOCK) { return mLastReturnCode; } } } /// /// If the session handle is , gets a descriptive string for the . /// public static string LastErrorString { get { lock (sessionLOCK) { return mLastReturnString; } } } /// /// Creates and initialize a Libusb-1.0 USB session handle. /// /// /// A instance must be created before calling any other Libusb-1.0 API function. /// public MonoUsbSessionHandle() : base(IntPtr.Zero, true) { lock (sessionLOCK) { IntPtr pNewSession = IntPtr.Zero; try { mLastReturnCode = (MonoUsbError)MonoUsbApi.Init(ref pNewSession); } catch (DllNotFoundException dllNotFound) { if (Helper.IsLinux) { throw new DllNotFoundException(DLL_NOT_FOUND_LINUX, dllNotFound); } else { throw new DllNotFoundException(DLL_NOT_FOUND_WINDOWS, dllNotFound); } } if ((int)mLastReturnCode < 0) { mLastReturnString = MonoUsbApi.StrError(mLastReturnCode); SetHandleAsInvalid(); } else { SetHandle(pNewSession); mSessionCount++; } } } /// /// /// /// protected override bool ReleaseHandle() { if (!IsInvalid) { lock (sessionLOCK) { MonoUsbApi.Exit(handle); SetHandleAsInvalid(); mSessionCount--; Debug.Print(GetType().Name + " : ReleaseHandle #{0}", mSessionCount); } } return true; } } }