You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Performance] Rewrite DirectWriteForwarder in C# to improve rendering performance #5305
The current code is written in C++/CLI and I think that can be optimized. Unfortunately, I have written very little C++/CLI myself but I suspect that the generated IL code is smaller and better performing.
Reacted by lindexi, Bastian Schmidt, kronic, Ryland, viniciusverasdossantos, HispidaBytes, Daniel Svensson, Ruslan , Paulus Pärssinen and Andrii Kurdiumov
No, I did it because I needed a way to build it on Linux using open source tools for wine-mono. I didn't expect it to be useful for upstream.
It probably needs to be cleaned up. The few C functions needed could be moved to an existing dll, or maybe ComWrappers would remove the need for them. There's still TrueTypeSubsetter which I didn't touch at all, it doesn't seem to be commonly used and could be moved to pure C++ I think. And the C# code probably shouldn't be mixed in with existing C++ code.
It also needs build system updates as I just used my own build system (my requirements were to build on Linux with Framework Mono, so the existing build files were not usable for my purposes).
I'm skeptical that this will improve performance. We still have to call into dwrite.dll so the native interop is just done in a different place.
Maybe I can at least put something together so you can do performance testing, once I find some free time.
Hey, this is a great idea and I've actually been working in my free time on converting DirectWriteForwarder to C# for the past couple of weeks. The performance from the move from C++/CLI shouldn't be that noticeable since, as @madewokherd stated, we're still calling into dwrite.dll. But, there are other advantages, here are some in no particular order:
Trimming support. The .Net Trimmer does not support C++/CLI assembly analysis so it might remove code that is used in DirectWriteForwarder which can produce exceptions that are hard to diagnose (Eg. .net 5 trimming causes crash on copying text #3903).
NativeAOT support. NativeAOT does not support C++/CLI assemblies at all, and if I remember correctly, the team responsible for NativeAOT does not plan on adding support for it. (COM interop support runtimelab#306)
Crossgen support (This one I'm not 100% sure). I think Crossgen does not support C++/CLI assemblies so we may be leaving performance on the table here.
Ease of development. I think most people in the community that would like to contribute on WPF are better in C# than C++ because I think they all used C# and/or WPF before wanting to contribute here (I might be totally wrong and this statement is not in any way data-driven). Also, most of the code in WPF is already in C# so this would be good. The ease of development might also help optimizing the C# code after the port.
It's a legacy technology (I think, I wasn't able to find an official statement but I remember reading it somewhere).
Probably others that I couldn't think of off the top of my head.
For now, the prototype that I'm working on is not open source because it's not working yet, but I'm making progress. I took a slightly different approach than @madewokherd, I use structs for DWrite objects that I wrap in a CriticalHandle so the lifetime management is done by the GC and we almost never have to manually release them. We don't really need ComWrapper because if I recall correctly, DWrite is not "true COM". Most of DWrite objects are created by there parent object and one-way only (DWrite -> Managed).
Keep in mind that what I said might be totally untrue but for now, what I've done seems to be working.
We would also need confirmation from someone in the WPF team that they would be interested in a community PR for this, because if it's not built-in, the usefulness would be really limited.
Thanks!
Reacted by Adam Caviness, Rogier van der Hee and Andrii Kurdiumov
Apparently the part I had trouble with was implementing the IDWriteFontCollectionLoader and IDWriteFontFileLoader interfaces on the C# side. We would sometimes get calls to these interfaces after calling the corresponding IDWriteFactory::Unregister* method.
I don't remember exactly why that was a problem, but I was convinced at the time that I couldn't fix it while using builtin COM support to implement the interface, and I didn't want to rewrite it based on delegates.
Incidentally, that's the sort of reference cycle involving unmanaged objects that I don't think the GC will be able to detect for you.
I didn't hit this yet so maybe my app doesn't go far enough or it's something specific to built-in COM. I'll look into it once I hit this but thanks for the info!
My current plan for the port is this:
Remove reference to DirectWriteForwarder in PresentationCore.
Add every class that existed DirectWriteForwarder and that are required by PresentationCore.
Implement every required method as throw NotImplementedException.
Start a demo app using the built assemblies and wait for NotImplementedException.
Port the method from C++/CLI to C#.
Start again from 4.
I'm currently doing steps 4 to 6. This might not be the most efficient way but I wanted to do it small steps at a time to make sure that every method works and that it doesn't start breaking everywhere. This is a direct port so there are no changes other than porting C++/CLI code to C#.
Reacted by lindexi, Robin Lindner, Bastian Schmidt, kronic, Adam Caviness and Rogier van der Hee
Reacted by lindexi, Steve, Robin Lindner, Bastian Schmidt and Adam Caviness
I have created a benchmark for DWrite in general. This benchmark covers the direct call of the methods via COM.
The COM overhead cannot be read out here, of course, but perhaps it would be a future consideration to no longer use DWrite but to rewrite the complete font rendering in C#.
I have some updates, I ported a good chunk of C++/CLI code to C#, enough to run a simple app without needing any C++/CLI code. I'll start cleaning my port and I will push it to my fork when it's in a "good enough" state. There's still a large task of testing everything but from my initial testing, it seems to work.
One nice thing that I noticed is that I was now able to trim a simple WPF app with few or no linker hints/configurations.
Reacted by Bastian Schmidt, Vishal Sharma, Robin Lindner, Rogier van der Hee, lindexi, Michael Dietrich, DavidHollman and aiqinxuancai
My next step is to do some testing using WPF samples and then try to split this branch in multiple PRs to try and merge it progressively.
Oh that seems great. Good work!
A small thing, besides the unimplemented methods: Couldn't this theoretically be converted to a struct that doesn't use an object but an int (the only constructor call of Span is an int and by using int it is not boxed). This would allow the compiler to allocate the span on the stack.
Since I don't know all the background, feel free to be critical :). Code Snippet / Span
@deeprobin That's some nice suggestions but for now I'm not really looking at performance optimizations. Span could probably be generic because according to this comment, it was created before C# supported generics. I'll try to take a deeper look at your suggestions once I'm done with the full port of DirectWriteForwarder to managed.
Why does it show unmanaged[Cdecl, Cdecl]? That's wrong in a few ways and should either be just [Cdecl] (unlikely) or [Stdcall, MemberFunction] (most technically correct), or just [MemberFunction] (also works, is correct, and the typical way to bind such function pointers)
The long num3 = *(long*)(*(long*)value + 40) is also "buggy" and won't do the right thing in many scenarios (such as 32-bit).
It looks like this is calling IDWriteFontCollection::FindFamilyName, in which case a better way to generate a trim safe signature is (noting the below is just using all unsafe for simplicity):
This minimizes the IL required, keeps things correct, efficient, etc. Whether or not GC.KeepAlive(_fontCollection) is required also depends on the type of _fontCollection. I wouldn't expect it in many typical usage scenarios that aim to minimize allocations and general overhead.
@miloush Where did you find the code in your screenshot ? I can't find it anywhere in the WPF repo and I'm pretty sure I haven't introduced the code in your screenshot.
Are you sure you're screenshot is not decompiled code from DirectWriteForwarder ? It looks a lot like it's this method decompiled:
I think the main issue is how do you know what method value+40 is. lpVtbl[5] is marginally better, but I guess the answer is it is the one that the method is called after. And it wasn't easy to check the family name and whether it is encoded correctly.
Either way I was wrong, sorry everyone. My bad for not using a native debugger. I guess the conclusion is having them generated as planned would actually improve the debugging situation from what it is now!
Activity
madewokherd commentedon Sep 14, 2021
Hi, I did this last year but I needed a small C component to get around some COM interop issues. https://github.com/madewokherd/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/DirectWriteForwarder/CPP/DWriteWrapper/Factory.cs
deeprobin commentedon Sep 14, 2021
@madewokherd Oh cool 👍🏼 Is in this already in Pull Request?
madewokherd commentedon Sep 14, 2021
No, I did it because I needed a way to build it on Linux using open source tools for wine-mono. I didn't expect it to be useful for upstream.
It probably needs to be cleaned up. The few C functions needed could be moved to an existing dll, or maybe ComWrappers would remove the need for them. There's still TrueTypeSubsetter which I didn't touch at all, it doesn't seem to be commonly used and could be moved to pure C++ I think. And the C# code probably shouldn't be mixed in with existing C++ code.
It also needs build system updates as I just used my own build system (my requirements were to build on Linux with Framework Mono, so the existing build files were not usable for my purposes).
I'm skeptical that this will improve performance. We still have to call into dwrite.dll so the native interop is just done in a different place.
Maybe I can at least put something together so you can do performance testing, once I find some free time.
ThomasGoulet73 commentedon Sep 17, 2021
Hey, this is a great idea and I've actually been working in my free time on converting DirectWriteForwarder to C# for the past couple of weeks. The performance from the move from C++/CLI shouldn't be that noticeable since, as @madewokherd stated, we're still calling into dwrite.dll. But, there are other advantages, here are some in no particular order:
For now, the prototype that I'm working on is not open source because it's not working yet, but I'm making progress. I took a slightly different approach than @madewokherd, I use structs for DWrite objects that I wrap in a CriticalHandle so the lifetime management is done by the GC and we almost never have to manually release them. We don't really need ComWrapper because if I recall correctly, DWrite is not "true COM". Most of DWrite objects are created by there parent object and one-way only (DWrite -> Managed).
Keep in mind that what I said might be totally untrue but for now, what I've done seems to be working.
We would also need confirmation from someone in the WPF team that they would be interested in a community PR for this, because if it's not built-in, the usefulness would be really limited.
Thanks!
madewokherd commentedon Sep 17, 2021
Apparently the part I had trouble with was implementing the IDWriteFontCollectionLoader and IDWriteFontFileLoader interfaces on the C# side. We would sometimes get calls to these interfaces after calling the corresponding IDWriteFactory::Unregister* method.
I don't remember exactly why that was a problem, but I was convinced at the time that I couldn't fix it while using builtin COM support to implement the interface, and I didn't want to rewrite it based on delegates.
Incidentally, that's the sort of reference cycle involving unmanaged objects that I don't think the GC will be able to detect for you.
ThomasGoulet73 commentedon Sep 17, 2021
I didn't hit this yet so maybe my app doesn't go far enough or it's something specific to built-in COM. I'll look into it once I hit this but thanks for the info!
My current plan for the port is this:
I'm currently doing steps 4 to 6. This might not be the most efficient way but I wanted to do it small steps at a time to make sure that every method works and that it doesn't start breaking everywhere. This is a direct port so there are no changes other than porting C++/CLI code to C#.
deeprobin commentedon Sep 19, 2021
@ThomasGoulet73
Thank you for taking a look at this. If you need some assistance, I can help you 😄.
deeprobin commentedon Oct 8, 2021
I have created a benchmark for DWrite in general. This benchmark covers the direct call of the methods via COM.
The COM overhead cannot be read out here, of course, but perhaps it would be a future consideration to no longer use DWrite but to rewrite the complete font rendering in C#.
Benchmark on
AMD Ryzen 5 3600 (6-Core): https://files.deeprobin.de/dwrite-bench/report/Source Code: https://github.com/deeprobin/dwrite-benchmark
@ThomasGoulet73 But of course the first step is to get rid of the C++/CLI code.
ThomasGoulet73 commentedon Nov 25, 2021
I have some updates, I ported a good chunk of C++/CLI code to C#, enough to run a simple app without needing any C++/CLI code. I'll start cleaning my port and I will push it to my fork when it's in a "good enough" state. There's still a large task of testing everything but from my initial testing, it seems to work.
One nice thing that I noticed is that I was now able to trim a simple WPF app with few or no linker hints/configurations.
deeprobin commentedon Nov 25, 2021
@ThomasGoulet73 Oh thats nice. Thanks for the time you put into this.
ThomasGoulet73 commentedon Dec 1, 2021
I pushed my changes to a branch in my fork https://github.com/ThomasGoulet73/wpf/tree/managed-dwrite for those of you who want to try it. There are few methods that are still not implemented because I didn't hit them yet.
My next step is to do some testing using WPF samples and then try to split this branch in multiple PRs to try and merge it progressively.
deeprobin commentedon Dec 1, 2021
Oh that seems great. Good work!
A small thing, besides the unimplemented methods: Couldn't this theoretically be converted to a
structthat doesn't use anobjectbut anint(the only constructor call ofSpanis anintand by usingintit is not boxed). This would allow the compiler to allocate the span on the stack.Since I don't know all the background, feel free to be critical :).
Code Snippet / Span
ThomasGoulet73 commentedon Dec 6, 2021
@deeprobin That's some nice suggestions but for now I'm not really looking at performance optimizations. Span could probably be generic because according to this comment, it was created before C# supported generics. I'll try to take a deeper look at your suggestions once I'm done with the full port of DirectWriteForwarder to managed.
48 remaining items
lindexi commentedon Sep 10, 2025
@miloush What the generated classes do you means?
miloush commentedon Sep 10, 2025
The COM wrappers:
Clearly that's the cool way doing it for trimmability, just pointing out there is a hidden cost. No action needed.
franchyd commentedon Sep 10, 2025
Was this using CSWin32 or would it benefit from #7007
miloush commentedon Sep 10, 2025
I think that is cswin32
tannergooding commentedon Sep 10, 2025
Why does it show
unmanaged[Cdecl, Cdecl]? That's wrong in a few ways and should either be just[Cdecl](unlikely) or[Stdcall, MemberFunction](most technically correct), or just[MemberFunction](also works, is correct, and the typical way to bind such function pointers)The
long num3 = *(long*)(*(long*)value + 40)is also "buggy" and won't do the right thing in many scenarios (such as 32-bit).It looks like this is calling
IDWriteFontCollection::FindFamilyName, in which case a better way to generate a trim safe signature is (noting the below is just using all unsafe for simplicity):Given the following struct
This minimizes the IL required, keeps things correct, efficient, etc. Whether or not
GC.KeepAlive(_fontCollection)is required also depends on the type of_fontCollection. I wouldn't expect it in many typical usage scenarios that aim to minimize allocations and general overhead.ThomasGoulet73 commentedon Sep 10, 2025
@miloush Where did you find the code in your screenshot ? I can't find it anywhere in the WPF repo and I'm pretty sure I haven't introduced the code in your screenshot.
Are you sure you're screenshot is not decompiled code from DirectWriteForwarder ? It looks a lot like it's this method decompiled:
wpf/src/Microsoft.DotNet.Wpf/src/DirectWriteForwarder/CPP/DWriteWrapper/FontCollection.cpp
Line 14 in 348310e
miloush commentedon Sep 10, 2025
@ThomasGoulet73 hmm you might be right!
miloush commentedon Sep 10, 2025
I think the main issue is how do you know what method
value+40is.lpVtbl[5]is marginally better, but I guess the answer is it is the one that the method is called after. And it wasn't easy to check the family name and whether it is encoded correctly.Either way I was wrong, sorry everyone. My bad for not using a native debugger. I guess the conclusion is having them generated as planned would actually improve the debugging situation from what it is now!
h3xds1nz commentedon Sep 10, 2025
Yeah that's the decompiled C++/CLI source, which is always a nightmare.
Unfortunately we ain't moving from this state for at least another few years it seems, 0 commits in the past 2 months 😀
Migrate DWrite Factory to managed.
Migrate DWrite FontCollectionLoader to managed.
Migrate DWrite Factory to managed.
Migrate DWrite FontCollectionLoader to managed.
Migrate DWrite FontCollectionLoader to managed.
Reintroduce IDWriteFactory.CreateTextAnalyzer HRESULT validation