Dynamically load dll from android_assets folder

寵の児 提交于 2019-12-08 03:09:26
Mike Stonis

Here is an example of writing out assemblies to a Plugins folder and then reading them in and loading at runtime.

Make sure that you have your assemblies that you want to have go to the Assets folder set to a Build Action of AndroidAsset. See screenshot below.

Please Note: You might need to change the extension to .mp3. See here. I didn't have this issue though.

Once you do that, you should be able to get the assets by using the Asset Manager. You can load them up or do whatever with them. Here is a sample of reading them into memory and the writing out the name.

const String pluginPath = "Plugins";

var pluginAssets = Assets.List(pluginPath);
foreach (var pluginAsset in pluginAssets)
{
    var file = Assets.Open(pluginPath + Java.IO.File.Separator + pluginAsset);

    using (var memStream = new MemoryStream())
    {
        file.CopyTo(memStream);

        //do something fun.
        var assembly = System.Reflection.Assembly.Load(memStream.ToArray());
        Console.WriteLine(String.Format("Loaded: {0}", assembly.FullName));
    }

}

In release mode, please be mindful that the Mono for Android is going to perform a static analysis of your libraries to perform a size optimization. If you are loading assemblies after this, then you may not have features that should have been included. The screenshot below shows the standard linking configuration for a release build. There are some flags and configurations that you can add to your code to help prevent linking (Xamarin Docs on Linking), but I am not sure that there will be too much that you can do for dynamically loaded libraries.

This is not a direct answer to your question - I've no idea about loading assemblies from assets.

However, I do have quite a lot of experience of loading plugins in mvvmcross.


In mvx, we load platform specific plugins on droid by simply adding the dll as a refernce to the ui project and then calling Assembly.Load at runtime. This seems to work well.

Further, the same approach can be used in full windows applications - eg Wpf.

However, the same approach cannot be used on MonoTouch, Wp or WinRt - JIT and security/sandbox restrictions mean that you have to use some ui platform code to actually inject a code reference instead of using assembly.load. For more info, see http://slodge.blogspot.co.uk/2012/10/build-new-plugin-for-mvvmcrosss.html?m=1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!