@@ -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,13 @@ protected override void Destroy(bool disposing)
245
243
{
246
244
texture . Dispose ( ) ;
247
245
}
246
+
247
+ _myStream ? . Dispose ( ) ;
248
+ }
249
+
250
+ if ( _myBytesPin . IsAllocated )
251
+ {
252
+ _myBytesPin . Free ( ) ;
248
253
}
249
254
250
255
if ( ! disposing )
@@ -285,6 +290,8 @@ internal struct InfoMarshalData
285
290
}
286
291
287
292
private readonly Dictionary < uint , Texture > _textures = new Dictionary < uint , Texture > ( ) ;
293
+ private readonly StreamAdaptor _myStream ;
294
+ private GCHandle _myBytesPin ;
288
295
289
296
#region Imports
290
297
[ DllImport ( CSFML . Graphics , CallingConvention = CallingConvention . Cdecl ) , SuppressUnmanagedCodeSecurity ]
0 commit comments