@@ -41,10 +41,10 @@ public Font(string filename) : base(sfFont_createFromFile(filename))
4141 ////////////////////////////////////////////////////////////
4242 public Font ( Stream stream ) : base ( IntPtr . Zero )
4343 {
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 ) ;
4848
4949 if ( IsInvalid )
5050 {
@@ -62,16 +62,14 @@ public Font(Stream stream) : base(IntPtr.Zero)
6262 public Font ( byte [ ] bytes ) :
6363 base ( IntPtr . Zero )
6464 {
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 ) ;
7269
7370 if ( IsInvalid )
7471 {
72+ _myBytesPin . Free ( ) ;
7573 throw new LoadingFailedException ( "font" ) ;
7674 }
7775 }
@@ -245,6 +243,13 @@ protected override void Destroy(bool disposing)
245243 {
246244 texture . Dispose ( ) ;
247245 }
246+
247+ _myStream ? . Dispose ( ) ;
248+ }
249+
250+ if ( _myBytesPin . IsAllocated )
251+ {
252+ _myBytesPin . Free ( ) ;
248253 }
249254
250255 if ( ! disposing )
@@ -285,6 +290,8 @@ internal struct InfoMarshalData
285290 }
286291
287292 private readonly Dictionary < uint , Texture > _textures = new Dictionary < uint , Texture > ( ) ;
293+ private readonly StreamAdaptor _myStream ;
294+ private GCHandle _myBytesPin ;
288295
289296 #region Imports
290297 [ DllImport ( CSFML . Graphics , CallingConvention = CallingConvention . Cdecl ) , SuppressUnmanagedCodeSecurity ]
0 commit comments