我正在导出一个可以从非托管代码调用的方法,但该函数本身位于托管 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)
{
}
这告诉我这是一个看似任意的错误。我仍然想了解为什么编译器认为这是一个问题。