File: DependencyLoader.cs

package info (click to toggle)
opentk 1.1.4c%2Bdfsg-2.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 68,640 kB
  • sloc: cs: 525,501; xml: 277,501; ansic: 3,597; makefile: 41
file content (90 lines) | stat: -rw-r--r-- 2,396 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using OpenTK;

namespace Examples
{
    class DependencyLoader : IDisposable
    {
        bool disposed;
        readonly List<IntPtr> LoadedLibraries = new List<IntPtr>();

        enum TargetCpu
        {
            x86,
            x86_64,
        }

        static readonly TargetCpu Cpu = IntPtr.Size == 4 ? TargetCpu.x86 : TargetCpu.x86_64;

        public void LoadDependencies()
        {
            string path = Path.Combine("Dependencies", Cpu == TargetCpu.x86 ? "x86" : "x64");

            if (Directory.Exists(path))
            {
                if (Configuration.RunningOnWindows)
                {
                    foreach (var file in Directory.GetFiles(path, "*.dll"))
                    {
                        IntPtr lib = NativeMethods.LoadLibrary(file);
                        if (lib == IntPtr.Zero)
                        {
                            Debug.Print("Failed to load dependency {0} with {1}", file,
                                Marshal.GetLastWin32Error());
                        }
                        else
                        {
                            LoadedLibraries.Add(lib);
                            Debug.Print("Loaded dependency {0}", file);
                        }
                    }
                }
            }
        }

        static class NativeMethods
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            internal static extern IntPtr LoadLibrary(string dllName);

            [DllImport("kernel32.dll", SetLastError = true)]
            internal static extern int FreeLibrary(IntPtr dll);
        }

        #region IDisposable Members

        void Dispose(bool manual)
        {
            if (!disposed)
            {
                if (manual)
                {
                    foreach (var lib in LoadedLibraries)
                    {
                        NativeMethods.FreeLibrary(lib);
                    }
                }

                disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~DependencyLoader()
        {
            Dispose(false);
        }

        #endregion
    }
}