Managed C++ with .NET Core 2.1

前端 未结 3 980
执笔经年
执笔经年 2021-02-19 18:20

We have a library written in C++. To make it more compatible with our more modern .NET projects, we wrapped this C++ library in another .NET project. It works fine when referenc

相关标签:
3条回答
  • 2021-02-19 18:44

    PInvoke seems to be the only way to go.

    Put the library DLL in the solution folder (the actual C++ DLL, not a .NET wrapper).

    NOTE: Don't reference the DLL in the solution, just place the DLL in the same folder.

    Then use DLL Import to access the methods:

    static class NativeMethods
    {
        [DllImport("MyLibrary.dll", EntryPoint = "ValidateAdminUser", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean ValidateAdminUser(String username, String password);
    }
    

    NOTE 2: It still requires the .NET Core project to run in x86 architecture.

    0 讨论(0)
  • 2021-02-19 18:49

    As others pointed out, .NET Core does not currently support C++/CLI (aka "managed C++"). If you want to call into native assemblies in .NET Core, you must use PInvoke (as you discovered).

    You can also compile your .NET Core project in AnyCPU, as long as you keep around both 32- & 64-bit versions your native library and add special branching logic around your PInvoke calls:

    using System;
    
    public static class NativeMethods
    {
        public static Boolean ValidateAdminUser(String username, String password)
        {
            if (Environment.Is64BitProcess)
            {
                return NativeMethods64.ValidateAdminUser(username, password);
            }
            else
            {
                return NativeMethods32.ValidateAdminUser(username, password);
            }
        }
    
        private static class NativeMethods64
        {
            [DllImport("MyLibrary.amd64.dll", EntryPoint = "ValidateAdminUser", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
            public static extern Boolean ValidateAdminUser(String username, String password);
        }
    
        private static class NativeMethods32
        {
            [DllImport("MyLibrary.x86.dll", EntryPoint = "ValidateAdminUser", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
            public static extern Boolean ValidateAdminUser(String username, String password);
        }
    }
    

    Where you have your MyLibrary.amd64.dll and MyLibrary.x86.dll assemblies in the same directory. It would be nice if you could put relative paths into DllImport and have x86/amd64 subdirectories, but I haven't figured out how to do that.

    0 讨论(0)
  • 2021-02-19 18:53

    No it does not. .NET core is cross platform but C++/CLI is not, the Microsoft C++ compiler requires Windows.

    0 讨论(0)
提交回复
热议问题