5

我正在导出一个可以从非托管代码调用的方法,但该函数本身位于托管 c++ 项目中。以下代码导致编译器错误:

error C2526: 'System::Collections::Generic::IEnumerator<T>::Current::get' : C linkage function cannot return C++ class 'System::Collections::Generic::KeyValuePair<TKey,TValue>'
error C2526: 'System::Collections::Generic::Dictionary<TKey,TValue>::KeyCollection::GetEnumerator' : C linkage function cannot return C++ class 'System::Collections::Generic::Dictionary<TKey,TValue>::KeyCollection::Enumerator'

extern "C"
__declspec( dllexport )
bool MyMethod(std::string &name, std::string &path, std::map<std::string, std::string> &mymap)
{
  System::Collections::Generic::Dictionary<System::String ^, System::String^> _mgdMap = gcnew System::Collections::Generic::Dictionary<System::String ^, System::String ^>();

  // Blah blah processing
}

稍微研究一下这个错误,这个问题通常与标记为“extern“C”'的方法的定义有关。那么为什么它完全关心方法内部发生的事情呢?

如果我注释掉 Dictionary 初始化,或者将其切换到 HashTable,一切都会编译得很漂亮。

以下方法也有效 - 如果不是在本地定义字典,而是通过在方法中初始化它来避免局部变量。

bool status = CallAnotherMethod(ConvertToDictionary(mymap));

其中 ConvertToDictionary 被声明为

System::Collections::Generic::Dictionary<System::String ^, System::String ^>^ ConvertToDictionary(std::map<std::string, std::string> &map)
{
}

这告诉我这是一个看似任意的错误。我仍然想了解为什么编译器认为这是一个问题。

4

2 回答 2

2

很抱歉发布了 necroposting,但我需要与某人分享我的快乐 :)

似乎您可以通过创建两个包装器来解决这个问题 - 一个用于标记为“extern C”的外部调用,一个用于内部调用。在这种情况下,“extern C”之外的所有内容都将像往常一样执行 .NET 代码。

此处的 topicstarter 已回答 - C++/CLI->C# error C2526: C links function cannot return C++ class

void DummyInternalCall(std::string &name, std::string &path, std::map<std::string, std::string> &mymap)
{
   System::Collections::Generic::Dictionary<System::String ^, System::String^> _mgdMap =  gcnew System::Collections::Generic::Dictionary<System::String ^, System::String ^>();

  // Blah blah processing
}

extern "C" __declspec( dllexport )
bool MyMethod(std::string &name, std::string &path, std::map<std::string, std::string> &mymap)
{
   DummyInternalCall(name, path, mymap);
}
于 2014-10-12T15:54:13.837 回答
2

如果你用 C++ 编写一个要从 C 调用的函数,你不能在它的接口(参数和返回类型)中使用任何不是纯 C 的东西。这里所有的参数都是 C++ 对象。

于 2014-03-08T00:53:41.960 回答