<p>Problem (simplified to make things clearer):</p>

<ul>
1. there is one statically-linked static.lib that has a function that increments:

<pre><code>
    extern int CallCount = 0;
    int TheFunction()
    {
        void *p = &CallCount;
        printf("Function called");
        return CallCount++;
    }
</code></pre>

2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:
<pre><code>
    int Managed::CallLibFunc()
    {
        return TheFunction();
    }
</code></pre>

3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:

<pre><code>
    static void Main(string[] args)
    {
        Managed c1 = new Managed();
        int val1 = c1.CallLibFunc();
        // value is zero

        AppDomain ad = AppDomain.CreateDomain("NewDomain");
        Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
        int val2 = c.CallLibFunc();
        // value is one 
    }
</code></pre>
</ul>

<p>Question:</p>

<p>Based on what I have read in Essential .NET  Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?</p>

<p>Thank you very much everyone!</p>

[{'answer_id': 73075, 'author': 'gnobal', 'author_id': 7748, 'author_profile': 'https://Stackoverflow.com/users/7748', 'pm_score': 3, 'selected': True, 'text': '<p>My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.</p>\n\n<p><a href="http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/98cbabe0-33d6-4775-a3a7-04e71b7498dd/" rel="nofollow noreferrer">This link</a> shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.</p>\n\n<p><a href="http://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/" rel="nofollow noreferrer">This link</a> is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I\'m not sure this can help you but maybe you\'ll find this useful to create some kind of a workaround.</p>\n'}, {'answer_id': 73135, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 0, 'selected': False, 'text': "<p>In short, maybe.  AppDomains are purely a managed concept.  When an AppDomain is instantiated  it doesn't map in new copies of the underlying DLLs, it can reuse the code already in memory (for example, you wouldn't expect it to load up new copies of all the System.* assemblies, right?)</p>\n\n<p>Within the managed world all static variables are scoped by AppDomain, but as you point out this doesn't apply in the unmanaged world.</p>\n\n<p>You could do something complex that forces a load of a unique managed.dll for each app domain, which would result in a new version of the static lib being brought along for the ride.  For example, maybe using Assembly.Load with a byte array would work, but I don't know how the CLR will attempt to deal with the collision in types if the same assembly is loaded twice.</p>\n"}, {'answer_id': 73289, 'author': 'Seb Rose', 'author_id': 12405, 'author_profile': 'https://Stackoverflow.com/users/12405', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t think we\'re getting to the actual issue here - <a href="http://www.ddj.com/windows/184405853" rel="nofollow noreferrer">see this DDJ article</a>.</p>\n\n<p>The default value of the loader optimization attribute is SingleDomain, which "causes the AppDomain to load a private copy of each necessary assembly\'s code". Even if it were one of the Multi domain values "every AppDomain always maintains a distinct copy of static fields".</p>\n\n<p>\'managed.dll\' is (as its name implies) is a managed assembly. The code in static.lib has been statically compiled (as IL code) into \'managed.dll\', so I would expect the same behaviour as Lenik expects....</p>\n\n<p>... unless static.lib is a static export library for an unmanaged DLL. Lenik says this is not the case, so I\'m still unsure what\'s going on here.</p>\n'}, {'answer_id': 93134, 'author': 'Rick Minerich', 'author_id': 9251, 'author_profile': 'https://Stackoverflow.com/users/9251', 'pm_score': 0, 'selected': False, 'text': '<p>Have you tried running in separate processes? A static library should not share memory instances outside of it\'s own process.</p>\n\n<p>This can be a pain to manage, I know. I\'m not sure what your other options would be in this case though.</p>\n\n<p>Edit: After a little looking around I think you could do everything you needed to with the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process_members.aspx" rel="nofollow noreferrer">System.Diagnostics.Process</a> class. You would have a lot of options at this point for communication but <a href="http://msdn.microsoft.com/en-us/library/kwdt6w2k(VS.71).aspx" rel="nofollow noreferrer">.NET Remoting</a> or WCF would probably be good and easy choices.</p>\n'}, {'answer_id': 157738, 'author': 'Lou Franco', 'author_id': 3937, 'author_profile': 'https://Stackoverflow.com/users/3937', 'pm_score': 0, 'selected': False, 'text': '<p>These are the best two articles I found on the subject</p>\n\n<ul>\n<li><a href="http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx</a></li>\n<li><a href="http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx</a></li>\n</ul>\n\n<p>The important part is:</p>\n\n<blockquote>\n  <p>RVA-based static fields are process-global.  These are restricted to scalars and value types, because we do not want to allow objects to bleed across AppDomain boundaries.  That would cause all sorts of problems, especially during AppDomain unloads.  Some languages like ILASM and MC++ make it convenient to define RVA-based static fields.  Most languages do not.</p>\n</blockquote>\n\n<p>Ok, so if you control the code in the .lib, I\'d try</p>\n\n<pre><code>class CallCountHolder {\n   public:\n     CallCountHolder(int i) : count(i) {}\n     int count;\n};\n\nstatic CallCountHolder cc(0);\nint TheFunction()\n{\n    printf("Function called");\n    return cc.count++;\n}\n</code></pre>\n\n<p>Since he said that RVA-based static fields are limited to scalars and value types.  An int array might also work.</p>\n'}, {'answer_id': 693295, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>After you call </p>\n\n<pre><code>Managed c1 = new Managed(); \n</code></pre>\n\n<p>Your managed.dll wrapper will be loaded into main app domain of you application. Till it will be there domain unmanaged stuff from static.lib  will be shared with other domains. \nInstead of creating separate process you just need to be sure (before each call) that managed.dll is not loaded into any application domain. </p>\n\n<p>Compare with that </p>\n\n<pre><code>static void Main(string[] args)\n{\n\n    {       \n                AppDomain ad = AppDomain.CreateDomain("NewDomain");\n                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n                int val2 = c.CallLibFunc();\n                //  Value is zero\n\n               AppDomain.Unload(ad)\n    }\n    {       \n                AppDomain ad = AppDomain.CreateDomain("NewDomain");\n                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n                int val2 = c.CallLibFunc();\n                //  I think value is zero\n\n               AppDomain.Unload(ad)\n    }\n\n\n}\n`\n</code></pre>\n\n<p>IMPORTANT and : If you add just one line JIT compiler will load managed.dll and the magic disappears.     </p>\n\n<pre><code>static void Main(string[] args)\n{\n\n    {       \n                AppDomain ad = AppDomain.CreateDomain("NewDomain");\n                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n                int val2 = c.CallLibFunc();\n                //  Value is zero \n\n               AppDomain.Unload(ad)\n    }\n    {       \n                AppDomain ad = AppDomain.CreateDomain("NewDomain");\n                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n                int val2 = c.CallLibFunc();\n                //  I think value is one\n\n               AppDomain.Unload(ad)\n    }\nManaged c1 = new Managed(); \n\n\n}\n</code></pre>\n\n<p>If you don\'t want to depend on such lines you can create another one wrapper ManagedIsolated.dll that will reference managed.dll and will make each call in separate domain with domain unload just after the call.  Main application will depend only on ManagedIsolated.dll types and Managed.dll will not be loaded into main app domain.</p>\n\n<p>That looks like a trick but may be it will be usefull for somebody.\n    `</p>\n'}]
['https://Stackoverflow.com/questions/72769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2341/']