PdfPig
PdfPig copied to clipboard
ReflectionGraphicsStateOperationFactory and NativeAOT builds
A follow up to #664 and a question / enquiry:
As mentioned in 664, ReflectionGraphicsStateOperationFactory is doing some things with reflection that can cause issues when using linker trimming or doing NativeAOT builds.
As I've been wanting to learn a bit about how SourceGenerators work, I wondered if if would be possible to generate the list of graphics operations with one, rather than having to enumerate all types in the library looking for classes that implement IGraphicsStateOperation at runtime.
So, I had a play and put together this: https://github.com/UglyToad/PdfPig/compare/master...Numpsy:PdfPig:source_gen
It's rather rough and glued together from generator samples, but the idea is that you can generate something like this at build time, and then just use the fixed collection of types with less runtime work:
Does anyone have any thoughts on if the idea might be useful to take beyond a learning exercise?
This has become a bit easier now, as it didn't work with .NET 4.5, but that's been removed by #795
I've tried using PdfPig with AOT and had trim warnings and an exception during runtime. Once I built my application with your fix, everything went fine. Is there a plan, to bring your code generation approach to main?
It needs a bit more work to be production ready, but I can have another look if there's interest.
I've updated my branch with all the latest changes for now anyway.
I am definitely interested. Did a lot research with libraries in different languages and PdfPig would be my preferred choice. Unfortunately I am depending on AOT. I didn't realize code generation in C# was a thing now too, but it's nice that it's leading to more compatibility here. Currently I know little about c# code generation myself, so not sure, if I would be much help, but let me know if i can assist anywhere else.
Now that everything has been updated to .NET 8 etc I'll have a go at doing a version using IIncrementalGenerator instead of ISourceGenerator as I gather that should be faster
@Numpsy I'm not very familiar with source generators but we could also take the approach to hard code stuf. This is the approach I took, see here https://github.com/BobLd/PdfPig/blob/caly-20240412/src/UglyToad.PdfPig/Graphics/ReflectionGraphicsStateOperationFactory.cs
it works very well with aot
That's all the generator actually creates, so if the list of items doesn't change much then just hardcoding it is simpler.
Feel free to create a PR when you have time @Numpsy. More than happy to review it and merge it
@jsiedentop We've merged some changes should fix some of the problems here - would you be able to test your case when we have a nightly build containing #832 and see if that works now?