简体   繁体   English

元帅 C# 字典到 C++(非托管)

[英]Marshal C# dictionary to C++ (unmanaged)

I'm currently working on a .NET Framework 4.7.2 application.我目前正在开发一个 .NET Framework 4.7.2 应用程序。 I need to use logic from an unmanaged C++ library.我需要使用来自非托管 C++ 库的逻辑。 I must not use C++/CLI (managed C++) .我不能使用 C++/CLI (managed C++)

I try to figure out how I can marshal a C# Dictionary to unmanaged C++:我试图弄清楚如何将 C# 字典编组到非托管 C++:

Dictionary<string, float> myData

Do you know, what would be the correct equivalent for Dictionary<string, float> in unmanaged C++?您知道吗,非托管 C++ 中Dictionary<string, float>的正确等效项是什么?

Thank you!谢谢!

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.如果您的字典很大并且 C++ 只需要查询几个值,或者更改过于频繁,请使用 COM 互操作。 Very easy to do due to extensive COM support in .NET runtime.由于 .NET 运行时中广泛的 COM 支持,非常容易做到。 Here's an example, use guidgen to generate GUID for the interface.下面是一个例子,使用 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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM