PInvokeHelper.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. namespace OpenCvSharp.Internal.Util;
  2. /// <summary>
  3. ///
  4. /// </summary>
  5. public static class PInvokeHelper
  6. {
  7. /// <summary>
  8. /// Checks whether PInvoke functions can be called
  9. /// </summary>
  10. public static void TryPInvoke()
  11. {
  12. try
  13. {
  14. var size = NativeMethods.core_Mat_sizeof();
  15. }
  16. catch (DllNotFoundException e)
  17. {
  18. DllImportError(e);
  19. }
  20. catch (BadImageFormatException e)
  21. {
  22. DllImportError(e);
  23. }
  24. }
  25. /// <summary>
  26. /// DllImportの際にDllNotFoundExceptionかBadImageFormatExceptionが発生した際に呼び出されるメソッド。
  27. /// エラーメッセージを表示して解決策をユーザに示す。
  28. /// </summary>
  29. /// <param name="ex"></param>
  30. public static void DllImportError(Exception ex)
  31. {
  32. throw CreateException(ex);
  33. }
  34. /// <summary>
  35. ///
  36. /// </summary>
  37. /// <param name="ex"></param>
  38. public static OpenCvSharpException CreateException(Exception ex)
  39. {
  40. if (ex is null)
  41. throw new ArgumentNullException(nameof(ex));
  42. /*StringBuilder message = new StringBuilder();
  43. if (System.Globalization.CultureInfo.CurrentCulture.Name.Contains("ja"))
  44. {
  45. message.AppendFormat("{0}\n", ex.Message);
  46. message.Append("*** P/Invokeが原因で例外が発生しました。***\n")
  47. .Append("以下の項目を確認して下さい。\n")
  48. .Append("(1) OpenCVのDLLが実行ファイルと同じ場所に置かれていますか? またはパスが正しく通っていますか?\n")
  49. .Append("(2) Visual C++ Redistributable Packageをインストールしましたか?\n")
  50. .Append("(3) OpenCVのDLLやOpenCvSharpの対象プラットフォーム(x86またはx64)と、プロジェクトのプラットフォーム設定が合っていますか?\n")
  51. .Append("\n")
  52. .Append(ex.ToString());
  53. }
  54. else
  55. {
  56. message.AppendFormat("{0}\n", ex.Message);
  57. message.Append("*** An exception has occurred because of P/Invoke. ***\n")
  58. .Append("Please check the following:\n")
  59. .Append("(1) OpenCV's DLL files exist in the same directory as the executable file.\n")
  60. .Append("(2) Visual C++ Redistributable Package has been installed.\n")
  61. .Append("(3) The target platform(x86/x64) of OpenCV's DLL files and OpenCvSharp is the same as your project's.\n")
  62. .Append("\n")
  63. .Append(ex.ToString());
  64. }
  65. return new OpenCvSharpException(message.ToString(), ex);*/
  66. return new OpenCvSharpException(ex.Message, ex);
  67. }
  68. }