Login Page - Create Account

Support Board


Date/Time: Mon, 20 May 2024 00:37:03 +0000



Post From: Sierra Chart Shared Variables

[2018-03-01 20:09:41]
JoseyWales - Posts: 67
In the most basic way, you could create a static struct that holds variables. Place the following code in a header file that you #include in each cpp file that needs access to the SharedData.

#ifndef SharedData_H
#define SharedData_H

#include "sierrachart.h"

enum SCStringArrayValues
{
  Value1,
  Value2,
  SCStringArraySize
};

struct MutualDataStruct
{
  int IntegerValue{};
  float FloatValue{};
  SCString SCStringValue{};

  SCString SCStringArray[SCStringArraySize]; // C style array of type SCString
  std::vector<SCString> SCStringVector; // C++ Vector style array of type SCString
};

static MutualDataStruct SharedData;

#endif SharedData_H

Of course rename the variables to something more descriptive than IntegerValue;

The curly braces are called uniform initialization a C++11 feature, which means the variables are initialized with default values when they are created. For integers and floats this means the variable will be 0, and for strings it will be blank "".

And in a study function you call whatever variable however you want:

      SharedData.IntegerValue = 3;
      SharedData.SCStringValue = "This is text";
      SharedData.SCStringArray[Value1] = "Hello";
      SharedData.SCStringVector.emplace_back("Hello Vector");

Do note that C style arrays must have their size known at compile time, which is one reason why I used an Enum value. The other being that it's wise to use a const named variable instead of a random "magic number", especially if it's being referred to from multiple cpp files. Less room for bugs that way.

You could also use a std::vector<SCString> and push_back()/emplace_back() each SCString to add it to the vector. Or maybe std::stack would better suit your needs.
http://www.cplusplus.com/reference/vector/vector/

Another thing to note is what happens when the study is recalculated? Should the vector's contents be cleared? If so, would that mess up another study that is referring to it? You could also make the struct more like a class and have it be Object-Oriented with function methods to handle the vector. Functions like SharedData.AddToSCStringArray() or SharedData.Clear() that calls the SCStringVector.clear() function and maybe assigns the other variables to 0. And if the vector is intended to be very large than you may want to declare it as a pointer so that the memory is on the heap.

std::vector<SCString>* SCStringVector = new std::vector<SCString>;

So a handful of little gotcha's depending on how complicated you want it to be. But single variables are simple and easy to work with.
Date Time Of Last Edit: 2018-03-01 20:37:31