Search code examples
excelc++-cliexcel-dna

ExcelDnaPack.exe that packs a C++/CLI library


I used ExcelDNA to create an Excel addin, packed into a single xll using ExcelDnaPack.exe. It works beautifully, until I add a reference to a dll created with a C++/CLI project (called CPPLibrary.dll) When I pack the CPPLibrary.dll the addin complains at runtime that it cannot find the dll. If I leave CPPLibrary.dll unpacked and just copy it in the same directory as the -packed.xll everything works. Is there a way to successfully pack a C++/CLI project into an ExcelDNa addin?

Thanks.


Solution

  • I ended up embedding the c++/cli as a resource, and in realtime when the excel dna addin gets loaded I extract the embedded dll to a file in disk and do a Assembly.LoadFrom(extracted path) Like this:

    private static void ExtractAndLoadCPPLibrary()
    {
        var executingAssembly = Assembly.GetExecutingAssembly();               
        string resource_path = "mydnaassembly.Embedded.CPPLibrary.dll";
        var version = executingAssembly.GetName().Version.ToString().Replace(".","_");
        var output_Path = Path.Combine(Path.GetTempPath(), "CPPLibrary_" + version + ".dll");
        if (!File.Exists(output_Path))
        {
            using (Stream cpplibrary_input = executingAssembly.GetManifestResourceStream(resource_path))
            using (var cpplibrary_output = File.Create(output_Path))
            {
                cpplibrary_input.CopyTo(cpplibrary_output);
            }
        }
        Assembly assembly = Assembly.LoadFrom(output_Path);
    }