Use TDictionary in C++ Builder XE2

3.2k views Asked by At

Currently I want to use TDitionary in C++ Buillder XE2

After I read the documentation I thought it should have been easy but I even can not create a TDictionary object...

My code:

#include <vcl.h>
#pragma hdrstop
#include <Generics.collections.hpp>
#include "TDictionaryTest.h"

#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;

void __fastcall TForm2::FormCreate(TObject *Sender)
{
    TDictionary__2 <String, String> *Dir = new  TDictionary__2<String, String>(0);
    delete Dir;
}

Error messages:

[ILINK32 Error] Error: Unresolved external '__fastcall           System::Generics::Collections::TDictionary__2<System::UnicodeString,   System::UnicodeString>::~TDictionary__2<System::UnicodeString, System::UnicodeString>()'  referenced from ...\PRACTICE\C++\WIN32\DEBUG\TDICTIONARYTEST.OBJ
[ILINK32 Error] Error: Unresolved external '__fastcall System::Generics::Collections::TEnumerable__1<System::Generics::Collections::TPair__2<System::UnicodeString, System::UnicodeString> >::~TEnumerable__1<System::Generics::Collections::TPair__2<System::UnicodeString, System::UnicodeString> >()' referenced from ...\PRACTICE\C++\WIN32\DEBUG\TDICTIONARYTEST.OBJ
[ILINK32 Error] Error: Unresolved external 'System::Generics::Collections::TDictionary__2<System::UnicodeString, System::UnicodeString>::' referenced from ...\PRACTICE\C++\WIN32\DEBUG\TDICTIONARYTEST.OBJ
[ILINK32 Error] Error: Unresolved external '__fastcall System::Generics::Collections::TDictionary__2<System::UnicodeString, System::UnicodeString>::TDictionary__2<System::UnicodeString, System::UnicodeString>(int)' referenced from ...\PRACTICE\C++\WIN32\DEBUG\TDICTIONARYTEST.OBJ
[ILINK32 Error] Error: Unable to perform link

Anyone has any idea? Thanks!

2

There are 2 answers

5
Remy Lebeau On BEST ANSWER

Like @mhtaqia said, C++ cannot instantiate Delphi's Generics classes yet, only consume them when they are created by Delphi code. For C++ code, you should use an STL std::map instead:

#include <map> 

void __fastcall TForm2::FormCreate(TObject *Sender) 
{ 
    std::map<String, String> *Dir = new std::map<String, String>; 
    delete Dir; 
} 

Or:

#include <map> 

void __fastcall TForm2::FormCreate(TObject *Sender) 
{ 
    std::map<String, String> Dir; 
}

On a side note: DO NOT ever use the TForm::OnCreate and TForm::OnDestroy events in C++. They are Delphi idioms that can produce illegal behavior in C++ as they can be triggered before your derived constructor and after your derived destructor, respectively. Use the actual constructor/destructor instead.

0
mh taqia On

TDictionary is only for accessing Delphi variables and fields. You can not use and instantiate it in C++ code. Template classes are usable when defined completely in a header file.