Skip to content

Commit ba5d9dd

Browse files
DllImportGenerator's marshalling
1 parent 23eb58a commit ba5d9dd

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

gm_dotnet_managed/GmodNET/GameConsoleWriter.cs

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,50 @@ public GameConsoleWriter(ILua lua)
4747

4848
Msg = (message) =>
4949
{
50-
byte[] string_array = Encoding.UTF8.GetBytes(message);
51-
fixed (byte* ptr = &string_array[0])
50+
byte* __message_gen_native = default;
51+
//
52+
// Setup
53+
//
54+
bool message__allocated = false;
55+
try
5256
{
53-
msg_func(ptr);
57+
//
58+
// Marshal
59+
//
60+
if (message != null)
61+
{
62+
int message__bytelen = (message.Length + 1) * 3 + 1;
63+
if (message__bytelen > 260)
64+
{
65+
__message_gen_native = (byte*)System.Runtime.InteropServices.Marshal.StringToCoTaskMemUTF8(message);
66+
message__allocated = true;
67+
}
68+
else
69+
{
70+
byte* path__stackptr = stackalloc byte[message__bytelen];
71+
{
72+
message__bytelen = System.Text.Encoding.UTF8.GetBytes(message, new System.Span<byte>(path__stackptr, message__bytelen));
73+
path__stackptr[message__bytelen] = 0;
74+
}
75+
76+
__message_gen_native = (byte*)path__stackptr;
77+
}
78+
}
79+
80+
//
81+
// Invoke
82+
//
83+
msg_func(__message_gen_native);
84+
}
85+
finally
86+
{
87+
//
88+
// Cleanup
89+
//
90+
if (message__allocated)
91+
{
92+
System.Runtime.InteropServices.Marshal.FreeCoTaskMem((System.IntPtr)__message_gen_native);
93+
}
5494
}
5595
};
5696
}

0 commit comments

Comments
 (0)