How to Pass a Parameter byRef to a Subclassed Thread

I can pass a parameter to a subclassed thread’s Constructor byRef, but then it has to be saved to a property of the subclass, at which point it’s no longer byRef.

I’m currently using the ugly workaround of passing an array of which I use only the 0th element, but I feel there should be something more elegant using a MemoryBlock or Ptr or some such, which I don’t know how to do.

If you have a parameter of type “ptr” in the threads constructor you can simply pass a property of type MemoryBlock to it. The thread stores the pointer in an own property of type “ptr” and you can use that in the Run event. All you write via the pointer goes directly in the MemoryBlock you assigned. You simply have to make sure that the MemoryBlock don’t go out of scope as long as the thread runs.

1 Like

Pass an instance of a class with one (or more) properties.

But it seems like might be a better way to do what you’re doing.

1 Like

I tried following your recommended setup, but the passed variable in the calling routine is not modified by the thread. Assuming it can be made to work, while possibly “purer”, it ends up being slightly more opaque and verbose than what I’m doing now, so maybe I’ll stick with it as Kem suggests.

Hi Julia

Can you explain why you need to store it ByRef?

2 Likes

The same reason you ever need to pass anything ByRef - I need the thread to be able to modify the value of the property in the calling object.

Maybe you can use a delegate to do the work?
Or is there no other way than storing the object (ByRef) ?

I think your current solution is the best / only way if you want the thread to manipulate that exact value. An alternative would be to wrap the data inside a class instance. I did log an enhancement a few years back (53332) to allow a variable to point to another variable which probably would have worked for you.

An alternative approach would be for the thread to have its own copy of the data and to raise a custom event with the new value when it changed.

Or you make it a singleton (could be in a dictionary, where the key is unique) somewhere?

A delegate to a Setter method is a great idea, I’ll have a look at that.

As suggested by Kem :slight_smile:

OOP frowns on singletons :slight_smile:

Here is an example file: property_mod_in_thread.xojo_binary_project

1 Like

Thank you!

i remember xojo can not copy objects.
i think your object is cast into something else, because you spoke about a subclass.