private void UnloadLibrary() { if (hModule != IntPtr.Zero) { Win32LibInterop.FreeLibrary(this.hModule); hModule = IntPtr.Zero; } }
private void LoadLibrary() { if (TargetLibraryFileName == null) { throw new ArgumentNullException("LibraryFileName"); } hModule = Win32LibInterop.LoadLibrary(TargetLibraryFileName); if (hModule == IntPtr.Zero) { throw new Exception(string.Format("{0}:{1}", Win32LibInterop.GetLastErrorMessage(), TargetLibraryFileName)); } }
private void DriverFunctionInterop() { ConstructorInfo notImpException = typeof(NotImplementedException).GetConstructor(Type.EmptyTypes); Type targetType = typeof(T); string typeName = targetType.Name; List <MethodInfo> methods = new List <MethodInfo>(); foreach (Type inheritedType in targetType.GetInterfaces()) { methods.AddRange(inheritedType.GetMethods()); } methods.AddRange(targetType.GetMethods()); foreach (MethodInfo methodInfo in methods) { string Win32_FunctionName = string.Format("{0}_{1}", TargetDriverPrefix, methodInfo.Name); IntPtr ptrfun = Win32LibInterop.GetProcAddress(this.hModule, Win32_FunctionName); //if (ptrfun == IntPtr.Zero) //{ // throw new Exception(string.Format("{0}:{1}", Win32LibInterop.GetLastErrorMessage(), Win32_FunctionName)); //} Type returnType = methodInfo.ReturnType; ParameterInfo[] Parameters = methodInfo.GetParameters(); Type[] paramTypes = new Type[Parameters.Length]; for (int i = 0; i < Parameters.Length; i++) { paramTypes[i] = Parameters[i].ParameterType; } // Define the method MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, returnType, paramTypes); // Create Method body, call the corresponding driver function //------------------------------------------------------------------------------------------- // The ILGenerator class is used to put op-codes (similar to assembly) into the // method ILGenerator genIL = methodBuilder.GetILGenerator(); if (ptrfun == IntPtr.Zero) { // If function is not exist in Ivi C driver dll, then throw not implemented exception. :( genIL.Emit(OpCodes.Newobj, notImpException); genIL.Emit(OpCodes.Throw); } else { // Loads method argument onto the stack for coming DLL call. // Satrt from 1 because 0 is index for 'this' which no use for our DLL call for (int i = 1; i <= paramTypes.Length; i++) { //By-Ref given parameters. genIL.Emit(OpCodes.Ldarg, i); } if (IntPtr.Size == 4) { // Check Processer Type genIL.Emit(OpCodes.Ldc_I4, ptrfun.ToInt32()); } else if (IntPtr.Size == 8) { genIL.Emit(OpCodes.Ldc_I8, ptrfun.ToInt64()); } else { throw new PlatformNotSupportedException(); } genIL.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, returnType, paramTypes); genIL.Emit(OpCodes.Ret); // Return } //------------------------------------------------------------------------------------------- } }