-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMarshallString.cs
122 lines (99 loc) · 3.29 KB
/
MarshallString.cs
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
public static class ExtensionString
{
public static string CustomReverse(this string script)
{
string result = null;
string strValue = script;
int strLength = strValue.Length;
// Allocate HGlobal memory for source and destination strings
IntPtr sourcePtr = Marshal.StringToHGlobalAnsi(strValue);
IntPtr destPtr = Marshal.AllocHGlobal(strLength + 1);
// The unsafe section where byte pointers are used.
if (sourcePtr != IntPtr.Zero && destPtr != IntPtr.Zero)
{
unsafe
{
byte *src = (byte *)sourcePtr.ToPointer();
byte *dst = (byte *)destPtr.ToPointer();
if (strLength > 0)
{
// set the source pointer to the end of the string
// to do a reverse copy.
src += strLength - 1;
while (strLength-- > 0)
{
*dst++ = *src--;
}
*dst = 0;
}
}
result = Marshal.PtrToStringAnsi(destPtr);
}
Marshal.FreeHGlobal(sourcePtr);
Marshal.FreeHGlobal(destPtr);
return result;
}
public static string LinqReverse(this string script)
{
var tmpString = new StringBuilder();
var reversedStr = script.Reverse();
foreach (var c in reversedStr)
{
tmpString.Append(c);
}
return tmpString.ToString();
}
}
// Unicode & try-finally
public static class ExtensionString
{
public static string CustomReverse(this string script)
{
string result = null;
string strValue = script;
int strLength = strValue.Length;
// Allocate HGlobal memory for source and destination strings
IntPtr sourcePtr = Marshal.StringToHGlobalUni(strValue);
IntPtr destPtr = Marshal.StringToHGlobalUni(strValue);
// The unsafe section where byte pointers are used.
try
{
if (sourcePtr != IntPtr.Zero && destPtr != IntPtr.Zero)
{
unsafe
{
ushort* src = (ushort*)sourcePtr.ToPointer();
ushort* dst = (ushort*)destPtr.ToPointer();
if (strLength > 0)
{
// set the source pointer to the end of the string
// to do a reverse copy.
src += strLength - 1;
while (strLength-- > 0)
{
*dst++ = *src--;
}
*dst = 0;
}
}
result = Marshal.PtrToStringUni(destPtr);
}
return result;
}
finally
{
Marshal.FreeHGlobal(sourcePtr);
Marshal.FreeHGlobal(destPtr);
}
}
public static string LinqReverse(this string script)
{
var tmpString = new StringBuilder();
var reversedStr = script.Reverse();
foreach (var c in reversedStr)
{
tmpString.Append(c);
}
return tmpString.ToString();
}
}