@@ -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,16 @@ protected override void Destroy(bool disposing)
245243 {
246244 texture . Dispose ( ) ;
247245 }
246+
247+ if ( myStream != null )
248+ {
249+ myStream . Dispose ( ) ;
250+ }
251+ }
252+
253+ if ( myBytesPin . IsAllocated )
254+ {
255+ myBytesPin . Free ( ) ;
248256 }
249257
250258 if ( ! disposing )
@@ -285,6 +293,8 @@ internal struct InfoMarshalData
285293 }
286294
287295 private readonly Dictionary < uint , Texture > _textures = new Dictionary < uint , Texture > ( ) ;
296+ private SFML . System . StreamAdaptor myStream = null ;
297+ private GCHandle myBytesPin ;
288298
289299 #region Imports
290300 [ DllImport ( CSFML . Graphics , CallingConvention = CallingConvention . Cdecl ) , SuppressUnmanagedCodeSecurity ]
0 commit comments