@@ -41,10 +41,10 @@ public Font(string filename) : base(sfFont_createFromFile(filename))
41
41
////////////////////////////////////////////////////////////
42
42
public Font ( Stream stream ) : base ( IntPtr . Zero )
43
43
{
44
- using ( var adaptor = new StreamAdaptor ( stream ) )
45
- {
46
- CPointer = sfFont_createFromStream ( adaptor . InputStreamPtr ) ;
47
- }
44
+ // Stream needs to stay alive as long as the Font instance is alive
45
+ // Disposing of it can only be done in Font's Dispose method
46
+ myStream = new StreamAdaptor ( stream ) ;
47
+ CPointer = sfFont_createFromStream ( myStream . InputStreamPtr ) ;
48
48
49
49
if ( IsInvalid )
50
50
{
@@ -62,16 +62,14 @@ public Font(Stream stream) : base(IntPtr.Zero)
62
62
public Font ( byte [ ] bytes ) :
63
63
base ( IntPtr . Zero )
64
64
{
65
- unsafe
66
- {
67
- fixed ( void * ptr = bytes )
68
- {
69
- CPointer = sfFont_createFromMemory ( ( IntPtr ) ptr , ( UIntPtr ) bytes . Length ) ;
70
- }
71
- }
65
+ // Memory needs to stay pinned as long as the Font instance is alive
66
+ // Freeing the handle can only be done in Font's Dispose method
67
+ myBytesPin = GCHandle . Alloc ( bytes , GCHandleType . Pinned ) ;
68
+ CPointer = sfFont_createFromMemory ( myBytesPin . AddrOfPinnedObject ( ) , ( UIntPtr ) bytes . Length ) ;
72
69
73
70
if ( IsInvalid )
74
71
{
72
+ myBytesPin . Free ( ) ;
75
73
throw new LoadingFailedException ( "font" ) ;
76
74
}
77
75
}
@@ -245,6 +243,16 @@ protected override void Destroy(bool disposing)
245
243
{
246
244
texture . Dispose ( ) ;
247
245
}
246
+
247
+ if ( myStream != null )
248
+ {
249
+ myStream . Dispose ( ) ;
250
+ }
251
+ }
252
+
253
+ if ( myBytesPin . IsAllocated )
254
+ {
255
+ myBytesPin . Free ( ) ;
248
256
}
249
257
250
258
if ( ! disposing )
@@ -285,6 +293,8 @@ internal struct InfoMarshalData
285
293
}
286
294
287
295
private readonly Dictionary < uint , Texture > _textures = new Dictionary < uint , Texture > ( ) ;
296
+ private SFML . System . StreamAdaptor myStream = null ;
297
+ private GCHandle myBytesPin ;
288
298
289
299
#region Imports
290
300
[ DllImport ( CSFML . Graphics , CallingConvention = CallingConvention . Cdecl ) , SuppressUnmanagedCodeSecurity ]
0 commit comments