简体   繁体   中英

How to Fix Load From Context Error when Calling C++ DLL Function in C# Application

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);
}

What you see is not an exception. It is just a warning shown by the debugger. If you run the application without debugging, this will not appear at all. Inside Visual Studio in the exception handling settings of the debugger you can disable these types of warnings.

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM