开发者

What is the correct syntax to specify a c++/cli class as a TValue type in a Dictionary

开发者 https://www.devze.com 2023-03-26 04:17 出处:网络
I am having problems with the syntax in c++/cli when I try to define a c++/cli value struct as a TValue in a Dictionary

I am having problems with the syntax in c++/cli when I try to define a c++/cli value struct as a TValue in a Dictionary

I am doing this because I want to maintain a map between a native class 开发者_StackOverflow社区pointer and a system::String (with String as the key), so have wrapped the native pointer in a struct.

value struct MyStruct
{
   NativeClass *m_p;
}

Dictionary<System::String ^, MyStruct> MyMap;

NativeClass* FindLigandModelMap(System::String ^file)
{
   MyStruct m;
   if (m_LigandToModelMap.TryGetValue(file, %m)) <--- ERROR HERE
      return(m.m_p);
   return(NULL);
}

Thi gives a compiler error: error C2664: 'System::Collections::Generic::Dictionary::TryGetValue' : cannot convert parameter 2 from 'MyStruct ^' to 'MyStruct %'

I have tried various declarations of MyStruct with no success.


There are lots of subtle syntax errors in your snippet, you may benefit from a C++/CLI primer:

  1. the value type declaration requires a semicolon. C++ rule
  2. Dictionary<> is a reference type, hat required. C++/CLI rule
  3. passing an argument by reference is implied by the declaration, don't use %. C++ rule
  4. NULL is not valid in managed code, you have to use nullptr. C++/CLI rule

Thus:

#include "stdafx.h"
#pragma managed(push, off)
class NativeClass {};
#pragma managed(pop)

using namespace System;
using namespace System::Collections::Generic;

value struct MyStruct
{
    NativeClass *m_p;
};   // <== 1

ref class Example {
public:
    Dictionary<System::String ^, MyStruct>^ MyMap;   // <== 2

    NativeClass* FindLigandModelMap(System::String ^file)
    {
        MyStruct m;
        if (MyMap->TryGetValue(file, m))  // <== 3
            return(m.m_p);
        return nullptr;  // <== 4
    }
    // etc...
};


Should be just

m_LigandToModelMap.TryGetValue(file, m)

In C++, byref arguments don't provide any caller-side hint.

0

精彩评论

暂无评论...
验证码 换一张
取 消