This repository was archived by the owner on Feb 3, 2023. It is now read-only.
forked from libgit2/libgit2sharp
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathGitStrArrayManaged.cs
More file actions
62 lines (50 loc) · 1.86 KB
/
GitStrArrayManaged.cs
File metadata and controls
62 lines (50 loc) · 1.86 KB
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
using System;
using System.Runtime.InteropServices;
namespace LibGit2Sharp.Core
{
/// <summary>
/// A git_strarray where the string array and strings themselves were allocated
/// with LibGit2Sharp's allocator (Marshal.AllocHGlobal).
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct GitStrArrayManaged : IDisposable
{
public GitStrArray Array;
public static GitStrArrayManaged BuildFrom(string[] strings)
{
return BuildFrom(strings, StrictUtf8Marshaler.FromManaged);
}
public static GitStrArrayManaged BuildFrom(FilePath[] paths)
{
return BuildFrom(paths, StrictFilePathMarshaler.FromManaged);
}
private static GitStrArrayManaged BuildFrom<T>(T[] input, Func<T, IntPtr> marshaler)
{
var pointers = new IntPtr[input.Length];
for (int i = 0; i < input.Length; i++)
{
var item = input[i];
pointers[i] = marshaler(item);
}
var toReturn = new GitStrArrayManaged();
toReturn.Array.Strings = Marshal.AllocHGlobal(checked(IntPtr.Size * input.Length));
Marshal.Copy(pointers, 0, toReturn.Array.Strings, input.Length);
toReturn.Array.Count = new UIntPtr((uint)input.Length);
return toReturn;
}
public void Dispose()
{
var count = checked((int)Array.Count.ToUInt32());
for (int i = 0; i < count; i++)
{
EncodingMarshaler.Cleanup(Marshal.ReadIntPtr(Array.Strings, i * IntPtr.Size));
}
if (Array.Strings != IntPtr.Zero)
{
Marshal.FreeHGlobal(Array.Strings);
}
// Now that we've freed the memory, zero out the structure.
Array.Reset();
}
}
}