Skip to content

Commit 63d8ce4

Browse files
SignalRTJosé Luis Santiago
authored andcommitted
Add IntPtrExtension
To manage PtrToString conversions
1 parent 2cdcc5a commit 63d8ce4

File tree

7 files changed

+64
-63
lines changed

7 files changed

+64
-63
lines changed

LLama/Extensions/IModelParamsExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ private static IReadOnlyDictionary<string, IntPtr> GetAvailableBufferTypes()
115115
var dev = NativeApi.ggml_backend_dev_get(i);
116116
var buft = NativeApi.ggml_backend_dev_buffer_type(dev);
117117

118-
var name = Marshal.PtrToStringAnsi(NativeApi.ggml_backend_buft_name(buft));
118+
var name = NativeApi.ggml_backend_buft_name(buft).PtrToString();
119119
if (string.IsNullOrEmpty(name))
120120
continue;
121121

@@ -165,4 +165,4 @@ private static IReadOnlyDictionary<string, IntPtr> GetAvailableBufferTypes()
165165

166166
return (LLamaModelTensorBufferOverride*)overrideArrayPin.Pointer;
167167
}
168-
}
168+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System;
2+
using System.Runtime.InteropServices;
3+
using System.Text;
4+
5+
namespace LLama.Extensions;
6+
7+
public static class IntPtrExtensions
8+
{
9+
10+
/// <summary>
11+
/// Converts a native UTF-8 string pointer to a managed string, returning a fallback value when no data is available.
12+
/// </summary>
13+
/// <param name="ptr">Pointer to a null-terminated UTF-8 string.</param>
14+
/// <param name="defaultValue">Value to return when the pointer is <see cref="IntPtr.Zero"/> or when the string is empty.</param>
15+
/// <returns>Managed string representation of the native data, or <paramref name="defaultValue"/> when unavailable.</returns>
16+
public static string PtrToStringWithDefault(this IntPtr ptr, string defaultValue="")
17+
{
18+
return ptr.PtrToString() ?? defaultValue;
19+
}
20+
21+
/// <summary>
22+
/// Converts a pointer to a null-terminated UTF-8 string into a managed string.
23+
/// </summary>
24+
/// <param name="ptr">Pointer to the first byte of a null-terminated UTF-8 string.</param>
25+
/// <returns>Managed string representation, or <c>null</c> when the pointer is zero or the string is empty.</returns>
26+
public static string? PtrToString(this IntPtr ptr )
27+
{
28+
if (ptr == IntPtr.Zero)
29+
return null;
30+
31+
#if NETSTANDARD2_0
32+
unsafe
33+
{
34+
var length = 0;
35+
var current = (byte*)ptr;
36+
while (current[length] != 0)
37+
length++;
38+
39+
if (length == 0)
40+
return null;
41+
42+
var buffer = new byte[length];
43+
Marshal.Copy(ptr, buffer, 0, length);
44+
return Encoding.UTF8.GetString(buffer);
45+
}
46+
#else
47+
return Marshal.PtrToStringUTF8(ptr);
48+
#endif
49+
}
50+
51+
}

LLama/Native/MtmdContextParams.cs

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -51,35 +51,11 @@ public static MtmdContextParams Default()
5151
PrintTimings = native.print_timings,
5252
NThreads = native.n_threads,
5353
Verbosity = native.verbosity,
54-
ImageMarker = PtrToString(native.image_marker),
55-
MediaMarker = PtrToString(native.media_marker)
54+
ImageMarker = native.image_marker.PtrToString(),
55+
MediaMarker = native.media_marker.PtrToString()
5656
};
5757
}
5858

59-
private static string? PtrToString(IntPtr ptr)
60-
{
61-
if (ptr == IntPtr.Zero)
62-
return null;
63-
64-
#if NETSTANDARD2_0
65-
unsafe
66-
{
67-
var length = 0;
68-
var current = (byte*)ptr;
69-
while (current[length] != 0)
70-
length++;
71-
72-
if (length == 0)
73-
return string.Empty;
74-
75-
var buffer = new byte[length];
76-
Marshal.Copy(ptr, buffer, 0, length);
77-
return Encoding.UTF8.GetString(buffer);
78-
}
79-
#else
80-
return Marshal.PtrToStringUTF8(ptr);
81-
#endif
82-
}
8359

8460
/// <summary>
8561
/// Convert the managed representation to a native structure, pinning strings for the duration of the scope.

LLama/Native/NativeApi.Mtmd.cs

Lines changed: 2 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,35 +9,7 @@ namespace LLama.Native;
99
/// </summary>
1010
public static partial class NativeApi
1111
{
12-
/// <summary>
13-
/// Convert a UTF-8 encoded native string pointer into a managed <see cref="string"/>.
14-
/// Returns <c>null</c> when the pointer is zero.
15-
/// </summary>
16-
public static string? PtrToStringUtf8(IntPtr ptr)
17-
{
18-
if (ptr == IntPtr.Zero)
19-
return null;
20-
21-
#if NETSTANDARD2_0
22-
unsafe
23-
{
24-
var current = (byte*)ptr;
25-
var length = 0;
26-
while (current[length] != 0)
27-
length++;
28-
29-
if (length == 0)
30-
return string.Empty;
31-
32-
var buffer = new byte[length];
33-
Marshal.Copy(ptr, buffer, 0, length);
34-
return Encoding.UTF8.GetString(buffer);
35-
}
36-
#else
37-
return Marshal.PtrToStringUTF8(ptr);
38-
#endif
39-
}
40-
12+
4113
/// <summary>
4214
/// Native context parameters returned by <see cref="mtmd_context_params_default"/>.
4315
/// </summary>
@@ -59,7 +31,7 @@ internal struct mtmd_context_params
5931
/// Retrieve the default multimodal marker text.
6032
/// </summary>
6133
public static string? MtmdDefaultMarker()
62-
=> PtrToStringUtf8(mtmd_default_marker());
34+
=> mtmd_default_marker().PtrToString();
6335

6436
[DllImport(mtmdLibraryName, EntryPoint = "mtmd_context_params_default", CallingConvention = CallingConvention.Cdecl)]
6537
internal static extern mtmd_context_params mtmd_context_params_default();

LLama/Native/SafeLLamaSamplerHandle.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Runtime.InteropServices;
34
using System.Text;
5+
using LLama.Extensions;
46

57
namespace LLama.Native;
68

@@ -119,7 +121,7 @@ public string GetName(int index)
119121
if (index < 0 || index >= Count)
120122
throw new ArgumentOutOfRangeException(nameof(index));
121123

122-
return Marshal.PtrToStringAnsi(llama_sampler_name(llama_sampler_chain_get(this, index))) ?? "Unknown Name";
124+
return llama_sampler_name(llama_sampler_chain_get(this, index)).PtrToStringWithDefault("Unknown Name");
123125

124126
[DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
125127
static extern IntPtr llama_sampler_name(IntPtr smpl);
@@ -904,4 +906,4 @@ public interface ICustomSampler
904906
/// Create a clone of this sampler
905907
/// </summary>
906908
ICustomSampler Clone();
907-
}
909+
}

LLama/Native/SafeMtmdEmbed.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ public string? Id
195195
return WithHandle(ptr =>
196196
{
197197
var idPtr = NativeApi.mtmd_bitmap_get_id(ptr);
198-
return NativeApi.PtrToStringUtf8(idPtr);
198+
return idPtr.PtrToString();
199199
});
200200
}
201201
set

LLama/Native/SafeMtmdInputChunk.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System;
2-
using System.Runtime.InteropServices;
2+
using LLama.Extensions;
33

44
namespace LLama.Native;
55

@@ -91,7 +91,7 @@ public string Id
9191
return WithHandle(ptr =>
9292
{
9393
var idPtr = NativeApi.mtmd_input_chunk_get_id(ptr);
94-
return Marshal.PtrToStringAnsi(idPtr) ?? string.Empty;
94+
return idPtr.PtrToStringWithDefault(string.Empty);
9595
});
9696
}
9797
}

0 commit comments

Comments
 (0)