Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 74440a6

Browse files
committed
Refactor Marshals
1 parent d01f25f commit 74440a6

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

src/runtime/CustomMarshaler.cs

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Linq;
23
using System.Runtime.InteropServices;
34
using System.Text;
45

@@ -41,23 +42,18 @@ public int GetNativeDataSize()
4142
public class StrMarshaler : MarshalerBase
4243
{
4344
private static readonly MarshalerBase Instance = new StrMarshaler();
45+
private static readonly Encoding PyEncoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32;
4446

4547
public override IntPtr MarshalManagedToNative(object managedObj)
4648
{
47-
Encoding encoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32;
4849
var s = managedObj as string;
4950

5051
if (s == null)
5152
{
5253
return IntPtr.Zero;
5354
}
5455

55-
int minByteCount = encoding.GetMaxByteCount(1);
56-
char[] cStr = s.ToCharArray(0, s.Length);
57-
byte[] bStr = new byte[encoding.GetByteCount(cStr) + minByteCount];
58-
encoding.GetBytes(cStr, 0, cStr.Length, bStr, 0);
59-
DebugUtil.PrintHexBytes(bStr);
60-
56+
byte[] bStr = PyEncoding.GetBytes(s + "\0");
6157
IntPtr mem = Marshal.AllocHGlobal(bStr.Length);
6258
try
6359
{
@@ -86,6 +82,7 @@ public static ICustomMarshaler GetInstance(string cookie)
8682
public class StrArrayMarshaler : MarshalerBase
8783
{
8884
private static readonly MarshalerBase Instance = new StrArrayMarshaler();
85+
private static readonly Encoding PyEncoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32;
8986

9087
public override IntPtr MarshalManagedToNative(object managedObj)
9188
{
@@ -96,11 +93,7 @@ public override IntPtr MarshalManagedToNative(object managedObj)
9693
return IntPtr.Zero;
9794
}
9895

99-
var totalStrLength = 0;
100-
foreach (string arg in argv)
101-
{
102-
totalStrLength += arg.Length + 1;
103-
}
96+
int totalStrLength = argv.Sum(arg => arg.Length + 1);
10497
int memSize = argv.Length * IntPtr.Size + totalStrLength * Runtime.UCS;
10598

10699
IntPtr mem = Marshal.AllocHGlobal(memSize);
@@ -110,8 +103,7 @@ public override IntPtr MarshalManagedToNative(object managedObj)
110103
IntPtr curStrPtr = mem + argv.Length * IntPtr.Size;
111104
for (var i = 0; i < argv.Length; i++)
112105
{
113-
Encoding encoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32;
114-
byte[] bStr = encoding.GetBytes(argv[i] + "\0");
106+
byte[] bStr = PyEncoding.GetBytes(argv[i] + "\0");
115107
Marshal.Copy(bStr, 0, curStrPtr, bStr.Length);
116108
Marshal.WriteIntPtr(mem + i * IntPtr.Size, curStrPtr);
117109
curStrPtr += bStr.Length;

0 commit comments

Comments
 (0)