2
votes

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 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.

2

2 Answers

7
votes

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...
};
2
votes

Should be just

m_LigandToModelMap.TryGetValue(file, m)

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