c++-cli - 面向 .net5 时的 C++/CLI 链接器错误 LNK2022

标签 c++-cli

我们正在将一组 C++/CLI 项目从以 .n​​etframework 471 为目标的 vs2017 转换为以 .net5 为目标的 vs2019。

以下代码将在以 .netframework471 为目标时进行编译和链接,但以 .net5 为目标时将生成链接器错误。请注意,它似乎只是使用 gcrootSystem::String^ 的方法,当方法 foobar 被注释掉时,项目构建和链接成功(意味着带有 gcrootSystem::Exception^ 参数的 foobar2 方法不会导致问题) .

1>MSVCMRTD_netcore.LIB(mstartup.obj) : error LNK2022: metadata operation failed (80131195) : 1>LINK : fatal error LNK1255: link failed because of metadata errors

// UnmanagedClassWithGcHandle.h
#pragma once
#include <vcclr.h>

class UnmanagedClassWithGcHandle
{
public:
   int age;
   // error LNK2022 : metadata operation failed(80131195) :  ( ONLY TARGETING .NET 5.0 )
   void foobar(gcroot<System::String^>);

   // this is successful
   void foobar2(gcroot<System::Exception^>);
};

#include "pch.h"
#include "UnmanagedClassWithGcHandle.h"

// UnamanagedClassWithCcHandle.cpp
void UnmanagedClassWithGcHandle::foobar(gcroot<System::String^>)
{
}

void UnmanagedClassWithGcHandle::foobar2(gcroot<System::Exception^>)
{
}

最佳答案

我遇到了完全相同的问题。问题在于:

#include <vcclr.h>

这是用于访问 gcroot 的旧文件。相反,您需要:

#include <msclr/gcroot.h>

这将引入 msclr 命名空间中的 gcroot。将您的代码更改为:

void foobar(msclr::gcroot<System::String^>);

而且您应该能够构建。

关于c++-cli - 面向 .net5 时的 C++/CLI 链接器错误 LNK2022,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68865539/

相关文章:

c# - MAPI 链接静态库 (LNK2019 : Unresolved External Symbol)

.net - ISO C++ 代码是否可以在 C++/CLI 中直接编译?

windows - C++ 信号量和 _popen 用法

C++/命令行界面 : how to store a managed reference inside a native class?

c++ - 在 .NET 中使用 Windows API 函数

arrays - 将 array<int^>^ 转换为 int*

Lambda 似乎在 VS2010 中的 ref 类中不起作用

windows - c++/cli DLL 在 Win 8.1 下失败

c# - C++/CLI 比 C# 快吗

c# - 使用 C++/CLI 桥连接 C++ 和 C# 代码