c# - 使用 .NET Core 2.1 的托管 C++

标签 c# c++ .net asp.net-core .net-core

我们有一个用 C++ 编写的库。为了使其与我们更现代的 .NET 项目更加兼容,我们将此 C++ 库包装在另一个 .NET 项目中。从完整的 .NET Framework 项目(4.5、4.6 等)引用它时,它工作正常。

我正在使用 .NET Core 2.1 创建一个新应用程序,我正在尝试引用这个“封装在 .NET C++ 库中”。在我的第一次尝试中,它失败了,说程序集无法加载。我通过安装 .NET Core SDK x86 并强制我的应用程序使用 x86 而不是 Any CPU 解决了这个问题。

我没有遇到任何构建错误,但是当我尝试在该库中实例化一个类时,出现以下异常:

<CrtImplementationDetails>.ModuleLoadException: The C++ module failed to load.
 ---> System.EntryPointNotFoundException: A library name must be specified in a DllImport attribute applied to non-IJW methods.
   at _getFiberPtrId()
   at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* )
   at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
   --- End of inner exception stack trace ---
   at <CrtImplementationDetails>.ThrowModuleLoadException(String errorMessage, Exception innerException)
   at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
   at .cctor()

.NET Core 2.1 完全支持这种情况吗?

最佳答案

正如其他人指出的那样,.NET Core does not currently support C++/CLI (又名“托管 C++”)。如果要在 .NET Core 中调用 native 程序集,则必须使用 PInvoke (如您所见)。

您还可以在 AnyCPU 中编译您的 .NET Core 项目,只要您保留 native 库的 32 位和 64 位版本并在 PInvoke 调用周围添加特殊的分支逻辑即可:

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

MyLibrary.amd64.dll 和 MyLibrary.x86.dll 程序集位于同一目录中。如果您可以将相对路径放入 DllImport 并拥有 x86/amd64 子目录,那就太好了,但我还不知道该怎么做。

关于c# - 使用 .NET Core 2.1 的托管 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51958187/

相关文章:

c++ - 将 boost foreach 与本身就是模板的项目一起使用

.net - sp 执行时阻止读取行

c# - 奇怪的异常场景 System.Net.Http MediaTypeHeaderValue 无法转换为 MediaTypeHeaderValue

.net - 以编程方式查看移动数据终端(笔记本电脑/平板电脑/等)是否连接到扩展坞

c# - 使用泛型类型 'IdentityUserRole<TKey>' 需要 1 个类型参数

时间:2018-01-18 标签:c#error : The modifier 'private ' is not valid for this item

c++ - 从 QT 中的主窗口发出信号

c++ - 是否有平台不将 std::time_t 表示为 unix 时间?

c# - Mode=TwoWay、UpdateSourceTrigger=PropertyChanged 或 LostFocus?

c# - 如何限制我的 Windows 应用程序生成进程的单个实例?