将 C# 字典封送至C++(非托管)

Marshal C# dictionary to C++ (unmanaged)

本文关键字:C++ 字典      更新时间:2023-10-16

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

我尝试弄清楚如何将 C# 字典封送到非托管C++:

Dictionary<string, float> myData

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

谢谢!

如果字典很小,请在具有键值结构的连续缓冲区中进行序列化。

如果字典很大且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 );