Marshal C# dictionary to C++ (unmanaged)

Viewed 1247

I'm currently working on a .NET Framework 4.7.2 application. I need to use logic from an unmanaged C++ library. I must not use C++/CLI (managed C++).

I try to figure out how I can marshal a C# Dictionary to unmanaged C++:

Dictionary<string, float> myData

Do you know, what would be the correct equivalent for Dictionary<string, float> in unmanaged C++?

Thank you!

1 Answers

If your dictionary is small, serialize in a continuous buffer with key-value structures.

If your dictionary is large and C++ only needs to query a couple of values, or changes too frequently, use COM interop. Very easy to do due to extensive COM support in .NET runtime. Here's an example, use guidgen to generate GUID for the interface.

// 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 );
Related