【发布时间】:2014-03-08 00:38:23
【问题描述】:
我正在导出一个可以从非托管代码调用的方法,但该函数本身存在于托管 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)
{
}
这告诉我这是一个看似任意的错误。我仍然想了解为什么编译器认为这是一个问题。
【问题讨论】:
-
你能解决这个问题吗?似乎我有类似的问题 - 无法从 C++/CLI 初始化 C# 类,我相信这是因为“extern C”要求编译器在创建字典或类之前知道它的大小,这是“ C" 语言 - 接口先于实现,它告诉编译器这个对象需要初始化多少内存,Hans Passant 在这里回答了 stackoverflow.com/questions/2718836/…
-
问题是我的类是用 C# 定义的,我不想在 C++/CLI 中复制它的实现 - 我如何告知 C++/CLI 这个类需要什么大小?
标签: c++ extern managed-c++ linkage vc90