1

I use TwinCAT to code a robot with many joints, each of which has some unique features. Some joints have absolute encoders, while someones need to be initialized in a specific way, etc.

I used a joint base class(function block), containing common methods. And inherited it into derived classes for all kinds of joints with unique methods. It works fine.

I really want to loop through the instances of different classes. Putting them into an array is my first thought. I know C++'s vector or Python's list suits this job perfectly. But it seems impossible in TwinCAT.

I tried the interface, however, the unique methods are unavailable through the interface.

I tried to use a method to return the instance according to the input index, but it can only return the instance of one predefined class (function block).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
secs ss
  • 11
  • 1

1 Answers1

0

I do not know of a direct, simple "typecast attempt" operator.

There is the __QUERYINTERFACE (and the related __System.IQueryInterface interface), that looks like a form of type casting. I have not used it in the past, and quickly reading through the documentation, it seems to be targeting people who are better than I am and understand why that non-standard, convoluted way to achieve type casts that work only on interface types is a good idea.

Then there is the straightforward (but verbose and not great from a design standpoint) solution of :

  • Defining an ENUM in which each type has an ID
  • Defining a STRUCT you will use in your joint array where each entry has both a type (from the ENUM) and a pointer.
  • Using pointer assignment to perform the cast (because you can get the value a pointer of one type into a pointer of a different type).

You will not win code elegance contests with this, but it works, and if it saves worse ugliness elsewhere, well, it may be the path of least ugliness.

In my work, I have found I almost never do that, because I usually find ways to keep the type-specific processing inside the function block. I will have a generic methods common to all instances that have no arguments, or only generic arguments. I use reference injection so that each instance knows enough about the rest of the system.

Fred
  • 6,590
  • 9
  • 20
  • Thank you Fred! Having suggestions from a pro helps a lot! I shall reconsider my program structure by adding more references to the joint class to keep the code clean. – secs ss Sep 01 '23 at 01:21