How to fix the load of context error when calling the C ++ DLL function in the C # application

advertisements

I'm trying to call a C++ function inside a dll from my C# application. The dll is from a program that would be installed on the user's machine, so the dll must be loaded at runtime. I'm getting the following exception:

Managed Debugging Assistant 'LoadFromContext' has detected a problem ...

Additional information: The assembly named 'Client.API' was loaded from '(path to dll file)' using the LoadFrom context. The use of this context can result in unexpected behavior for serialization, casting and dependency resolution. In almost all cases, it is recommended that the LoadFrom context be avoided. This can be done by installing assemblies in the Global Assembly Cache or in the ApplicationBase directory and using Assembly.Load when explicitly loading assemblies.

I don't really understand what this error means. And I don't know how to fix it for my situation. I've searched online but I haven't found very much helpful information. This is the code I am working with:

[DllImport("dmawin.dll")]
private static extern int LoginDialog(IntPtr pWndParent, string pStrTitle,
uint pFlags, [MarshalAs(UnmanagedType.LPWStr)] ref StringBuilder pStrDataSource,
int pDSLength, string pStrUsername, string pStrPassword, string pStrSchema);

private bool Login(string pDataSource, string pLoginName,
string pPassword, string pScheme)
{
    private const int MAX_DB_NAME = 256;
    IntPtr handle = ParentForm.Handle;
    var sb = new StringBuilder(pDataSource, MAX_DB_NAME);

    //function call
    LoginDialog(handle, null, flags, ref sb, MAX_DB_NAME, pLoginName,
    pPassword, pScheme);
}


Fix your debugger setting, this warning should be turned off. This MDA is normally only meant to warn a programmer when he did not mean to use Assembly.LoadFrom(). Since you cannot do anything about it, not your code, you have very little reason to pay attention to it.

In VS2015 use Debug > Windows > Exception Settings. In earlier versions use Debug > Exceptions. Expand Managed Debugging Assistants and untick "LoadFromContext". If you have everything ticked for some reason then you want to reset all settings, click the top node twice.

FWIW, the library you use is clearly written in a .NET language already. High odds that you'll want to talk to the author and ask if he supports a managed interface so you don't have to use [DllImport].