Libraries: TypeToBytes - page 6

 

The code converts a structure to a string

#include <Data_String.mqh>
#define  DEFINE_STRING(A)                        \
  struct STRING##A                              \
  {                                             \
  private:                                      \
    short Array[A];                             \
                                                \
  public:                                       \
    void operator =( const string Str )         \
    {                                           \
      ::StringToShortArray(Str, this.Array);    \
      return;                                   \
    }                                           \
                                                \
    string operator []( const int = 0 ) const   \
    {                                           \
      return(::ShortArrayToString(this.Array)); \
    }                                           \
  };
DEFINE_STRING(120) // An analogue of a string that has a maximum of 128 characters.
#undef  DEFINE_STRING

struct str_Message
  {
   int               cnt;
   bool              res;
   double            ter;
   STRING120          str;
  };
void OnStart()
  {
//---
   str_Message a;
   a.cnt = 10;
   a.res = false;
   a.ter = 20.0123;
   a.str = "hello world";
   Print(DATA_STRING::ToString(str1););
  }

// Результат
//2020.03.31 10:43:18.320	StructTest2 (EURUSD,H1)	CgAAAAClvcEXJgM0QGgAZQBsAGwAbwAgAHcAbwByAGwAZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA


How to do the reverse conversion? (from string to structure)

 
Sergey Likho:

The code converts the structure to a string

How to do the reverse conversion? (from string to structure)

const string Str = DATA_STRING::ToString(a); // Translated the structure into a string.

str_Message Tmp[1];

// Get an array of structures from the string
if (DATA_STRING::FromString(Str, Tmp))   
{
  ArrayPrint(Tmp);
  Print(Tmp[0].str[]);   
  
  Print(_R(Tmp) == a); // Verify that the data matches the original data.
}

// Get the structure from the string.
// Tmp[0] = DATA_STRING::FromString<str_Message>(Str); // This is possible if there is no assignment operator (see STRING120::operator =).
 
Another application of the library's capabilities.
 
//+------------------------------------------------------------------+
//|test.mq5 |
//|Copyright 2021, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <TypeToBytes.mqh> 


CONTAINER <uchar> Container;


int OnInit()
  {
//---

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialisation function|
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function|
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  }
//+------------------------------------------------------------------+


The yellow line of code does not compile anymore. It gives the following error (build 2980):

Any ideas what would solve the problem?

 
Enrique Dangeroux:

The yellow line of code does not compile anymore. It generates the following error (build 2980):

Any ideas what would solve the problem?

Forum on trading, automated trading systems and testing trading strategies

Libraries: SingleTesterCache

fxsaber, 2021.06.21 02:42 pm.

In TypeToBytes.mqh, replace {0} with {} everywhere.

 
Thank you.
 

Updated. Bypasses a feature that was found. Previously could negatively affect _ArrayCopy and CONTAINER.

 

I have written a function to save strings of any length to global variables using your library. I don't understand everything, so I'm sure I haven't used it 100%.

Any thoughts on more efficient use?

#include <TypeToBytes.mqh>


//--------------------------------------------------------------------------------------------------
string
GVarGetString(string name) {
        double dbl[];
        
        // Read the parts of the variable: Name, Name(1), Name(2), ...
        for (int i = 0; ; ++i) {
                string s = (i == 0)? "" : "(" + (string)i + ")";
                double t = GlobalVariableGet(name + s);
                if (t == 0)
                        break;
                
                MyArrayResize(dbl, i + 1);
                dbl[i] = t;
        }
        
        uchar tmp0[], tmp[], tmp1[];  
        _ArrayCopy(tmp0, dbl);
        if (tmp0[0] != 0)
                // Uncompressed
                return CharArrayToString(tmp0);
        else {
                // With compression
                ArrayCopy(tmp, tmp0, 0, 1);
                CryptDecode(CRYPT_ARCH_ZIP, tmp, tmp1, tmp1);
                return CharArrayToString(tmp1);
        }
}


//--------------------------------------------------------------------------------------------------
void
GVarSetString(string name, string val) {
        double dbl[];
        uchar tmp[];
        uchar zero[1];
        int cnt = CryptEncode(CRYPT_ARCH_ZIP, _R(val).Bytes, tmp, tmp);
        if (cnt >= StringLen(val)) {
                // Uncompressed
                string str[1];
                str[0] = val;
                _ArrayCopy(dbl, str);
        }
        else {
                // With compression
                _ArrayCopy(dbl, zero, 0, 0, 1);         // Byte[0] == 0 - with compression
                _ArrayCopy(dbl, tmp, 1);                // From byte[1] data
        }
        
        // Write the parts of the variable: Name, Name(1), Name(2), ...
        cnt = ArraySize(dbl);
        for (int i = 0; i < cnt; ++i) {
                string s = (i == 0)? "" : "(" + (string)i + ")";
                GlobalVariableSet(name + s, dbl[i]);
        }
        GlobalVariablesFlush();
}
 
Edgar Akhmadeev global variables using your library. I don't understand everything, so I'm sure I haven't used it 100%.

Any thoughts on more efficient use?

Check out this option.


It would also be convenient to use CONTAINER<double> for global variables .

Нужны ли глобальные переменные терминала типа string? - Используйте темплейты, чтобы разработчики платформы отвлекались на всякую блажь.
Нужны ли глобальные переменные терминала типа string? - Используйте темплейты, чтобы разработчики платформы отвлекались на всякую блажь.
  • 2017.04.08
  • Mikhail Dovbakh
  • www.mql5.com
и динамическое формирование имени массива не обязательно строкового. Отдельный тип глобальных переменных - скорее всего не добавят. таким образом можно записывать и считывать из глобальных переменных строки
 
fxsaber #:

Check out this option.


It would also be convenient to use CONTAINER<double> for global variables .

Thanks