noy*_*o88 4 c++ function stdmap
我在Visual c ++中有一个DLL项目和一个CLR项目.
DLL项目是导出std :: map类型函数的项目.我将从我的CLR项目中调用该函数.
来自DLL项目,staff.h
#ifdef STAFFS_EXPORTS
#define STAFFS_API __declspec(dllexport)
#else
#define STAFFS_API __declspec(dllimport)
#endif
#include <string>
#include <map>
namespace Staffs {
// other exported functions
....
//
extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;
}
Run Code Online (Sandbox Code Playgroud)
staff.cpp
namespace Staffs {
std::map<int, std::string> staffMap;
extern "C" auto GetStaffMap() -> std::map<int, std::string> {
return staffMap;
}
void display_json(json::value const & jvalue, utility::string_t const & prefix)
{
// some code being skipped here
.......
//
staffMap.insert(std::make_pair(key, value));
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试编译我的DLL项目时,我遇到了一些错误:
Error C2526 'GetStaffMap': C linkage function cannot return C++ class 'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>>' AmsCppRest c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.h 18
Error C2556 'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>> Staffs::GetStaffMap(void)': overloaded function differs only by return type from 'void Staffs::GetStaffMap(void)' AmsCppRest c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp 38
Error C2371 'Staffs::GetStaffMap': redefinition; different basic types AmsCppRest c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp 38
Run Code Online (Sandbox Code Playgroud)
我找不到与此问题相关的任何解决方案.
您无法使用C链接导出非平凡的C++类,并且编译器会在错误消息中告诉您.
问题是为什么你首先使用C链接?如果您不必使用C链接,请不要使用它.这将使事情变得更加复杂,因为您需要几乎所有东西的包装器.只要您使用相同的编译器就可以了.
所以在你的头文件和源文件中,extern "C"如果可以的话,从签名中删除(在任何一种情况下:从源文件中删除它,否则你重新定义那里导致后两个错误的函数).
如果无法删除该extern "C"部件,请尝试返回void指针(void*)而不是std::map将其转换为CLR项目中的地图指针.但这会迫使您使用托管C++作为CLR语言.
我不知道您的CLR项目是什么,但如果它是用托管C++编写的,那么您可以使用所有标准C++类型,因此C++链接非常好.如果您的CLR项目使用不同的语言(如C#),请考虑在托管C++中创建另一个项目并将其用作包装器C# dll <--> managed C++ dll <--> C++ dll.
| 归档时间: |
|
| 查看次数: |
434 次 |
| 最近记录: |