1

I'm having a strange memory issue. My code works for a while, and then I start getting strange results. I am downloading a font from storage, in byte[], and then trying to add it as a Memory font.

    PrivateFontCollection pfc = new PrivateFontCollection();


            var fontData = await _blobManager.Download(fontUrl);

            int dataLength = fontData.FileData.Length;
            IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
            Marshal.Copy(fontData.FileData, 0, ptrData, dataLength);

            pfc.AddMemoryFont(ptrData, dataLength);

            Marshal.FreeCoTaskMem(ptrData);

            var thisName = pfc.Families[0].Name;

However, this works the first few times, and then I start getting crazy results. Even though I am logging the length of the font collection, which starts at 0 count, as expected... on occasions, and old Font Family name is being reported in the thisFamily variable. Even though I confirm that the font downloaded as the correct family name.

It seems that maybe the previous sessions has not been cleared and then pfc.AddMemoryFont(ptrData, dataLength); has the old font loaded in that location still. Is this possible? Is there an obvious issue with my code that can cause spurious memory allocation issues?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Craig
  • 18,074
  • 38
  • 147
  • 248
  • 1
    According to this [SO q](https://stackoverflow.com/questions/60264471/privatefontcollection-is-failed-to-add-memory-font-under-net-core) you should not free the memory if you still want to use the font. – Klaus Gütter Oct 25 '20 at 09:48

0 Answers0