Loading C# dll in C++/CLI at runtime

95 Views Asked by At

I had a single Visual Studio solution with 2 projects: C# library (dll) and a C++/CLI application project in which this library was used. For simplicity, let's say library code is as follows:

namespace ClassLibrary
    {
    public interface ISomeClass
        {
            int Add(int a, int b);
        }

    public class SomeClass : ISomeClass
        {
        public int Result = 0;

        public int Add(int a)
            {
                return Result + a;
            }
        }
    }

In C++/CLI it was loaded as:

#using "relativePathToDll"
gcroot<ClassLibrary::SomeClass^> pSomeClass = gcnew ClassLibrary::SomeClass();

// Function call
pSomeClass->Add(5);
pSomeClass->Add(7);
// ...

I need to separate the projects into different Visual Studio solutions. I can gather the path to dll when projects are built/deployed, save it to environmental variables/registry and read it from there at runtime. What would be the best approach to load this dll dynamically at runtime from a given path in C++/CLI project? Are there any better approaches that would not require knowing the path to dll beforehand? Is it worth looking more into ways to modify load-time linking (as decribed here)?

I tried using LoadLibrary() but I can not manage to get it working. Most likely I fail to properly export functions on C# side. Also this method would be quite a hassle as it's required to define each function pointer manually (there are way more functions in actual codebase). If I understand correctly, only static functions are allowed for it to work.

I can modify the class library into a COM dll. Examples online show that reference is required before runtime (to .tlb file), which is not possible in this case either.

I have also tried what this comment by xiay suggested but could not get it working due to lack of examples online.

It might be worth mentioning that my C# library uses some other C# dlls. Will I need to load those separately too?

0

There are 0 best solutions below