Controlling how P/Invoked assemblies are loaded in

2019-08-12 12:54发布

问题:

I've got an application which needs to call some unmanaged code in a dll. I need to do these calls from multiple app domains and specifically want the assembly to be loaded into memory multiple times (once per app domain).

I've tried doing the following:

    Dim AppDomainSetup As New AppDomainSetup
    With AppDomainSetup
        .PrivateBinPath = "<Blah>"
        .LoaderOptimization = LoaderOptimization.MultiDomainHost
    End With

    Dim AppDomain As AppDomain = AppDomain.CreateDomain(String.Format("AppDomain-{0}", AppDomainCounter), Nothing, AppDomainSetup)
    AppDomainCounter += 1

    Dim Manager = CType(
        AppDomain.
        CreateInstanceAndUnwrap(
            System.Reflection.Assembly.
            GetExecutingAssembly.FullName,
        "<My Manager Class>"), AppDomainManager)
    Return Manager

AppDomainManager inherits from MarshalByRefobject and has a method on it which (eventually) calls

<DllImport("<Path>",
    EntryPoint:="<MethodName>",
    CallingConvention:=CallingConvention.Cdecl)>
Private Shared Function <MethodName>(
                                    <InAttribute(),
                                    MarshalAsAttribute(UnmanagedType.LPStr)>
                                    ByVal sig1 As String,
                                    <InAttribute(),
                                    MarshalAsAttribute(UnmanagedType.LPStr)>
                                    ByVal sig2 As String) As Integer

However, after doing some testing, it seems that a single (instance?) of the assembly is being loaded and shared between app domains. I'd hoped that the AppDomain.LoaderOptimization setting would've forced a unique copy per domain.

Is there any way I can force the CLR to load the assembly multiple times?