gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:19:46 26 4
gpt4 key购买 nike

我们有一个用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com