logo
down
shadow

How to read a struct containing array of structs from TwinCat to C#


How to read a struct containing array of structs from TwinCat to C#

Content Index :

How to read a struct containing array of structs from TwinCat to C#
Tag : chash , By : nseibert
Date : November 24 2020, 12:01 PM

I hope this helps . Using TwinCAT 3 ADS.Net for reading from PLC, I'm trying to read a struct containing array of structs, but the ReadAny command crashes with "Unable to marshal type" exception. , I tested successfully following code:
c# code:
    class Program
    {
        public static TcAdsClient client;
        static void Main(string[] args)
        {


            // Create the ADS Client
            using (client = new TcAdsClient())
            {
                // Establish Connection
                client.Connect(new AmsAddress("10.1.2.95.1.1", 851));
                int handle = client.CreateVariableHandle("PRG_AIS.stAds");

                AdsClass ads = (AdsClass)client.ReadAny(handle, typeof(AdsClass));
                ads.boolArr[0] = 1;
                client.WriteAny(handle, ads);
                Console.ReadLine();

            }
        }
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    class AdsClass
    {

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
        public byte[] boolArr = new byte[10];
    }
TYPE AdsStruct :
STRUCT
    bTestArray : ARRAY[0..9] OF BOOL;
END_STRUCT
END_TYPE
[StructLayout(LayoutKind.Sequential, Pack = 1)]
class AdsClass
{

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public InnerStruct[] strArr = new InnerStruct[10];
}

struct InnerStruct
{
    public byte bBoolTest;
    public int nIntTest;
}
TYPE AdsStruct  :
STRUCT
    stTestArray : ARRAY[0..9] OF InnerStruct;
END_STRUCT
END_TYPE

TYPE InnerStruct :
STRUCT
    bBoolTest : BOOL;
    nIntTest  : DINT;
END_STRUCT
END_TYPE

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Coldfusion 8: Array of structs to struct of structs


Tag : arrays , By : Francis
Date : March 29 2020, 07:55 AM
should help you out You will still need to convert to unixtime, but ArrayOfStructsSort might be faster. At least you can compare the two options.

passing an argument ( a struct in an array of structs within a struct) to a function in C


Tag : c , By : Sebastián Ucedo
Date : March 29 2020, 07:55 AM
it should still fix some issue I have a struct "course" and a function for it: , Change:
typedef struct Transcript_s
{
    char* name;
    struct Course** courseArray;
} Transcript;
typedef struct Transcript_s
{
    char* name;
    Course** courseArray; /* 'Course' is a typedef for 'struct Course_s'. */
} Transcript;
t -> courseArray = malloc(sizeof(struct Course) * (a+1));
t -> courseArray = malloc(sizeof(Course*) * (a+1));
free(t -> courseArray);
while (t->courseArray[a] != NULL)
{
    free(t->courseArray[a]->name); /* If name was dynamically allocated. */
    free(t->courseArray[a]);
}
free(t -> courseArray);

How to properly allocate memory for structs, arrays of structs inside a struct, and passing that array as a parameter


Tag : c , By : pepper
Date : March 29 2020, 07:55 AM
Hope that helps There is no struct S, only S which is a typedef of anonymous structure.
Define struct S too:
typedef struct S {
  char id;
  struct S *children[SIZE];
}S;
typedef struct S S;
struct S {
  char id;
  S *children[SIZE];
};
arr[0].children[0] = malloc(sizeof(S));

Write array of struct using TwinCAT.Ads through C# application


Tag : chash , By : dnyaneshwar
Date : March 29 2020, 07:55 AM
I hope this helps you . I guess you are missing the counterpart in the PLC. Please make sure that in your PLC you have declared an array of stations something like:
// I have it in a global variable list named: STG_Variables
stat_array_Var : array [0..5] of Station;
TcAdsClient AdsComClient = new TcAdsClient();
AdsComClient.Connect(NetID_TwinCat, 851);

int handle_array = AdsComClient.CreateVariableHandle("STG_Variables.stat_array_Var");

// get some test stations:
Station station = new Station();
Station station2 = new Station();
Station station3 = new Station();
Station station4 = new Station();
Station station5 = new Station();

Station[] station_plural = new Station[] { station, station2, station3, station4, station5 };

// write some stuff to recognize that write test worked
for (int i = 0; i < station_plural.Length; i++)
{
    station_plural[i].ClusterID = "ID: " + i.ToString();
}

// just use the normal WriteAny method without the new int[] { 5 } parameter!
// send it down to the plc
AdsComClient.WriteAny(handle_array, plural);
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public class Station
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
    public string ClusterID;
    public byte Tech_Type;
    [MarshalAs(UnmanagedType.I1)]
    public bool Status;
    [MarshalAs(UnmanagedType.I1)]
    public bool Reject;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 51)]
    public string Rej_Detail;
    public byte Rej_Catagory;
}
TYPE Station :
STRUCT
    ClusterID   : STRING[10];
    Tech_Type   : USINT;
    Status      : BOOL;
    Reject      : BOOL;
    Rej_Detail  : STRING[50];
    Rej_Catagory : USINT; 
END_STRUCT
END_TYPE

Write array of struct using TwinCAT.Ads through vb.net application


Tag : .net , By : John Q.
Date : March 29 2020, 07:55 AM
I wish did fix the issue. A reference for those who are having similar problems: The difference in data type for TwinCAT and VB can be found in Beckhoff website: https://infosys.beckhoff.com/english.php?content=../content/1033/tcsystemmanager/basics/TcSysMgr_DatatypeComparison.htm&id=
TwinCAT is using IEC61131-3 standard.
Related Posts Related QUESTIONS :
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • "The attribute names could not be inferred from bind attribute 'bind-value'" exception in Blazor
  • How to fix ''System.ArgumentException" in c#?
  • C#. Ref returning delegate for ref extension method
  • Swashbuckle Swagger generate an actual guid
  • Trying to make thousands of database calls simultaneously - they stack instead of running concurently
  • run mstest from cmd using testcontainer
  • How to make M:N (many-to-many) relationship where both M and N are the same entities?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com