gpt4 book ai didi

c# - C++/CLI->C# 错误 C2526 : C linkage function cannot return C++ class

转载 作者:太空狗 更新时间:2023-10-29 17:57:37 25 4
gpt4 key购买 nike

我有一个使用 VS2010 C# 构建的简单 .NET dll,它公开了一个类的 2 个静态成员

public class Polygon
{
public static void Test(int test) {}
public static void Test(List<int> test) {}
}

然后我从 VS2010 C++ 创建了一个控制台应用程序并在 _tmain 上面添加了这个函数

extern "C" void TestMe()
{
Polygon::Test(3);
}

添加引用和编译给我这个错误

1>WierdError.cpp(9): error C2526: 'System::Collections::Generic::List<T>::GetEnumerator' : C linkage function cannot return C++ class 'System::Collections::Generic::List<T>::Enumerator'
1> with
1> [
1> T=int
1> ]
1> WierdError.cpp(9) : see declaration of 'System::Collections::Generic::List<T>::Enumerator'
1> with
1> [
1> T=int
1> ]
1> WierdError.cpp(9) : see reference to class generic instantiation 'System::Collections::Generic::List<T>' being compiled
1> with
1> [
1> T=int
1> ]

我的一些观察:

  • 如果我删除 extern "C"它编译成功
  • 如果我重命名 Test(List<int> test) 编译成功至 Test2(List<int> test)

我的问题是,出了什么问题以及如何从 C++ 端修复它。

我目前的解决方法是在 C# 中重命名该方法,但我宁愿不必这样做,我感觉我的 C++ 项目中可能缺少一个设置。

编辑:

我在 C++ 中找到了更好的解决方法,看起来我可以将 .NET 调用包装在另一个函数中。

void wrapper()
{
Polygon::Test(3);
}

extern "C" void TestMe()
{
wrapper();
}

不得不这样做似乎很愚蠢,我想知道这是否是编译器错误?让我害怕的是使用这样的方法并且不得不担心 C# 开发人员稍后可能会添加这样的静态方法并破坏 C++ 构建。

最佳答案

我只是想在这里大胆尝试一下,理由如下:

在编译期间,MSVC 的 C++ 编译器看到 extern "C"function TestMe() 正在调用类中的函数 Test() 多边形Polygon 是编译器的不完整类型。我猜编译器看不到函数 Polygon::Test(3) 是返回一个不完整的类型还是返回任何东西,它决定它需要在那个时候返回一个错误以防类型结果证明不是普通的 C 风格 POD 类型。

上面的部分 MSVC 似乎是一个合理的假设,如(7.5/9“链接规范”)C++ 标准所说:

“从 C++ 到其他语言定义的对象以及从其他语言到 C++ 定义的对象的链接是实现定义的和语言相关的。只有当两种语言实现的对象布局策略足够相似时,这种链接才能实现实现。”

这可以解释当您删除 extern C 链接规范或替换对 Cstyle 函数的调用时错误消失的原因。

关于c# - C++/CLI->C# 错误 C2526 : C linkage function cannot return C++ class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6375882/

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