AnyCPU/x86/x64 for C# application and it's C++/CLI dependency

后端 未结 2 1956
攒了一身酷
攒了一身酷 2020-12-15 05:59

I\'m Windows developer, I\'m using Microsoft visual studio 2008 SP1. My developer machine is 64 bit.

The software I\'m currently working on is managed .exe written i

2条回答
  •  Happy的楠姐
    2020-12-15 06:34

    There is a way: to have an "AnyCPU" C# wrapper and a C++ project per architecture, and let the C# wrapper load the right C++ project at run time.

    For the C++ project, create one version per different architecture (x86, x64), and build them all. Then in the wrapper do:

    public class CppWrapper
    {
        // C++ calls that will be dynamically loaded from proper architecture:
        public static readonly Func MyCplusplusMethodUsableFromCsharpSpace;
    
        // Initialization:
        static CppWrapper()
        {
            if(Environment.Is64BitProcess)
            {
                MyCplusplusMethodUsableFromCsharpSpace = CppReferences64.MyCplusplusClass.Method;
                // Add your 64-bits entry points here...
            }
            else
            {
                MyCplusplusMethodUsableFromCsharpSpace = CppReferences32.MyCplusplusClass.Method;
                /* Initialize new 32-bits references here... */
            }
        }
    
        // Following classes trigger dynamic loading of the referenced C++ code
        private static class CppReferences64
        {
            public static readonly Func MyCplusplusMethod = Cpp64.MyCplusplusMethod;
            /* Add any64-bits references here... */
        }
        private static class CppReferences32
        {
            public static readonly Func MyCplusplusMethod = Cpp32.MyCplusplusMethod;
            /* Add any 32-bits references here... */
        }
    }
    

    And in the C++ code, I use the same sources as I said, but will compile to different namespace depending on the build architecture:

    #ifdef _M_X64
    namespace Cpp64 {
    #else
    namespace Cpp32 {
    #endif
        public ref class MyCPlusPlusClass
        {
            public: static __int64 Method(void) { return 123; }
        };
    }
    

提交回复
热议问题