samcragg / sharpkml

SharpKML is an implementation of the Open Geospatial Consortium (OGC) KML 2.2 standard developed in C#, able to read/write both KML files and KMZ files.
MIT License
158 stars 51 forks source link

SharpKml crashes in Android release build #49

Open GiselaNoci opened 1 year ago

GiselaNoci commented 1 year ago

I am using the latest version 6.0.0 SharpKML Core in an Android project C# under Visual Studio. If I do a DEBUG build of the code, the SharpKML library functions well. However if I do a RELEASE build of my code, I get the following exception on the first of the library functions I use: "The type initializer for 'SharpKml.Base.KmlFactory' threw an exception" The line of code on which the exception was generated is: KmlFile file = KmlFile.Load(fileStream);

samcragg commented 1 year ago

Is there any chance you could get me the full exception details please, including stack trace?

As you mentioned Android, I'm wondering if it's an issue with AOT, as the library internally uses reflection a lot.

Thanks

GiselaNoci commented 1 year ago

Hi Sam The attached two images give the full exception details - there is an overlap as I had to scroll the screen to get the full capture - so screen2.png repeats some of what is in screen1.png, but I am sure you will fathom it out. I also do the same application on IOS, so am trying to see if the crash happens there as well. Thanks and Regards Gisela screen2 screen1

GiselaNoci commented 1 year ago

Hi again I have tested on IOS and the problem does not occur there Regards Gisela

GiselaNoci commented 1 year ago

I cloned the SharpKML Code and have rebuilt it. I can thus narrow it down that the exception is generated by this function - for any type. private static Func ConstructType(Type type) { return Expression.Lambda<Func>(Expression.New(type)).Compile(); }

tipa commented 1 year ago

I am almost certain that this is due to trimming (e.g. when TrimMode=Full is used in the csproj). It can happen on any .NET project that uses trimming (not just Android).

Workaround: Add this to your csproj:

  <ItemGroup>
    <LinkDescription Include="LinkDescription.xml" />
  </ItemGroup>

and add a file LinkDescription.xml with this contents:

<?xml version="1.0" encoding="utf-8"?>
<linker>
  <assembly fullname="SharpKml.Core">
    <type fullname="*" />
  </assembly>
</linker>

It would be nice if the library could be made trimming-safe so this workaround isn't needed. https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/prepare-libraries-for-trimming