#Return floatPointer from IJE 1 and use that in IJE2

1 messages · Page 1 of 1 (latest)

safe osprey
#

Code:

void OnUpdate()
{
  var job1 = new();
  var job1Handle = job1.ScheduleParallel(state.Dependency);
  state.Dependency = new Job2() { Input = job1.Result }.ScheduleParallel(job1Handle);
}

unsafe struct Job1 : IJE
{
  public float* Result;
  void Execute(SomeICD value)
  {
    Result = (float*)UnsafeUtility.Malloc(1, 4, Allocator.TempJob);
    *Result = 1;
  }
}

unsafe struct Job2 : IJE
{
  public float* Input;
  void Execute(SomeICD value)
  {
    //Read the Input and do something.
  }
}

I got NullReferenceException: Object reference not set to an instance of an object when trying to use *Input inside Job2.

Thanks for reading.

bronze ore
#

Start by reviewing the difference between a class and a struct in C#

gusty kelp
#

Just allocate a native reference outside the jobs and pass it between them

bronze ore
#

job1 is a struct, therefore it lives on the stack of OnUpdate and a copy of it is passed into the job scheduling system by ScheduleParallel()

because of this, the pointer value of job1.Result will never be changed, because only an internal copy will be used when the job is actually executed

#

secondly, since you're copying the pointer value of Result while you're still in OnUpdate, job1 has not yet been executed when you read the pointer value

severe acorn
#

Expand on antitirt's reply:
This instance of struct var job1 = new();
and the instance that will be registered to the job scheduler job1.ScheduleParallel are 2 different copies, no more related to each other.

#

At the time of this call job1.ScheduleParallel the job does not actually execute. A copy of it is registered to the job scheduler then it waits til the time it can execute! That's why the method name is Schedule**, not Run nor Execute.

#

So at the time of this call Input = job1.Result, job1.Result is still a null pointer.

#

It's crutial to always remember that: inside this OnUpdate, no job has actually executed yet! They are only scheduled to run at a later time when the worker threads are free to them.

#

And because they are structs, their copy are stored on the job scheduler registry, not the original one you created inside that OnUpdate.

#
var v1 = new Vector3(1, 2, 3);
var v2 = v1;
v2.x = 5f;

Debug.Log(v1); // (1, 2, 3);
Debug.Log(v2); // (5, 2, 3);
#

Vector3 is also a struct and it's a great example for "structs are copied by value".

tiny fractal
#

Technically what you do there could work if you used a float** and allocated it before, but then you could've just allocated it before the job anyways lol.
But yeah, as tertle says, just use a NativeReference<float>