Structure reference CG

Hello. Is any way to use reference or pointer for stucture in CG?

CG / HLSL / GLSL etc all lack exact equivalents to either references or pointers. However all variables are actually kind of always references internally, it’s just the default behavior is to make copies.

examples:

// Verbose re-implementation of the step() function.
// Takes an input value and returns a new value of 0 or 1
float step(float value)
{
  if (value < 0.5)
    return 0.0;
  else
    return 1.0;
}

// Exactly the same as above, just adding an explicit "in" on the input variable.
// The "in" is implicit if there are no arguments.
float step([B]in[/B] float value)
{
  if (value < 0.5)
    return 0;
  else
    return 1;
}

// No longer returns value, but instead sets takes a second variable as an output
// but ignores that variable's initial value, just like out in c#.
void step([B]in[/B] float value, [B]out[/B] float outValue)
{
  if (value < 0.5)
    outValue = 0.0;
  else
    outValue = 1.0;
}

// Also doesn't return a value, but only has a single input which is treated as a reference.
void step(inout float value)
{
  if (value < 0.5)
    value = 0.0;
  else
    value = 1.0;
}

You can use the same inout argument for structs or matrices, or any variable type in HLSL. However shader compilers might be a little weird with using that last function example with a struct. Compilers are fine with functions that have no return and an inout for most variable types, but when using a struct it might complain that there’s no return, so just have it return true but you can just not use it and it’ll get compiled away.

struct myStruct {
  float value;
};

bool step(inout myStruct s)
{
  if (s.value < 0.5)
    s.value = 0.0;
  else
    s.value = 1.0;
  return true;
}

Thanks, what I want is sorting several structs (MyStruct1, MyStruct3 , MyStruc3) by int element. Still can’t imagine how I can do it without copy or rewriting them…tomorrow I’ll study your answer in detail))

Ah. It will be a “copy” in that case, there’s no avoiding it when it comes to reassigning variables. The inout “reference” only works with variables passed to and from function calls.

However understand with HLSL you never actually have any real control over memory and compilers will often do things you wouldn’t expect coming from a C++ or C# background.

example:

float myValueA = 1.0;
float myValueB = myValueA;
// do stuff with myValueB, never use myValueA;

No copy actually happens, the compiler is smart enough to know myValueB in this case really is just myValueA and ignore the new variable. In fact no variable declarations might occur in that code as written, compiler will just ignore all of that and just use the value 1.0 later if neither myValueA or myValueB are ever modified.