将C#字典序列化到C++(非托管代码)

3

我目前正在开发一个.NET Framework 4.7.2应用程序。我需要使用来自非托管C++库的逻辑。我不能使用C++/CLI(托管C++)

我试图找出如何将C#字典转换为非托管C++:

Dictionary<string, float> myData

您知道在非托管的C++中,Dictionary<string, float> 的正确等效是什么吗?

谢谢!


就我所知,我认为你做不到 - Dictionary 的内部数据结构并没有考虑与本地代码的编组。 - 500 - Internal Server Error
是的,没错。我刚刚偶然发现了std::map<std::string, int>类型。但我仍然遇到了类似的转换错误。 - accordo777
1
你也不能创建一个std::map,需要使用C++/CLI。你唯一真正的选择是将字典压缩成数组或公开create/add/destroy函数,以便在C++代码中构建std::map。当然,性能可能会受到一些影响。 - Hans Passant
1个回答

1
如果您的字典很小,可以使用键值结构在连续缓冲区中序列化。如果您的字典很大,且C++只需要查询几个值或者更改太频繁,则应使用COM互操作性。由于.NET运行时具有广泛的COM支持,因此非常容易实现。以下是一个示例,请使用guidgen生成接口的GUID。
// C# side: wrap your Dictionary<string, float> into a class implementing this interface.
// lock() in the implementation if C++ retains the interface and calls it from other threads.
[Guid( "..." ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
interface iMyDictionary
{
    void getValue( string key, out float value );
    void setValue( string key, float value );
}
[DllImport("my.dll")]
extern static void useMyDictionary( iMyDictionary dict );

// C++ side of the interop.
__interface __declspec( uuid( "..." ) ) iMyDictionary: public IUnknown
{
    HRESULT __stdcall getValue( const wchar_t *key, float& value );
    HRESULT __stdcall setValue( const wchar_t *key, float value );
};
extern "C" __declspec( dllexport ) HRESULT __stdcall useMyDictionary( iMyDictionary* dict );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接