
Decoding a Series of Messages Using the Stream-Oriented C Decode Functions
The above example is fine as a sample for decoding a single message, but what happens in the more typical scenario of having a long-running loop that continuously decodes messages? It will be necessary to put the decoding logic into a loop.
#include "employee.h" /* include file generated by ASN1C */ #include "rtxsrc/rtxStreamFile.h" main () { ASN1TAG msgtag; int msglen, stat; OSCTXT ctxt; PersonnelRecord employee; const char* filename = "message.dat" /* Step 1: Initialize a context variable for decoding */ if (berStrmInitContext (&ctxt) != 0) { /* initialization failed, could be a license problem */ printf ("context initialization failed (check license)\n"); return -1; } /* Step 2: Open the input stream to read data */ stat = rtxStreamFileCreateReader (&ctxt, filename); if (stat != 0) { rtxErrPrint (&ctxt); return stat; } for (;;) { /* Step 3: Test message tag for type of message received */ /* (note: this is optional, the decode function can be */ /* called directly if the type of message is known).. */ if ((stat = berDecStrmPeekTagAndLen (&ctxt, &tag, &len)) != 0) { rtxErrPrint (&ctxt); return stat; }if (msgtag == TV_PersonnelRecord) { /* Step 4: Call decode function (note: last two args */ /* should always be ASN1EXPL and 0).. */ stat = asn1BSD_PersonnelRecord (&ctxt, &employee, ASN1EXPL, 0); /* Step 5: Check return status */ if (stat == 0) { process received data in `employee' variable.. } else error processing... } else check for other known message types.. /* Need to reset all memory for next iteration */ rtxMemReset (&ctxt); } /* end of loop */ /* Step 6: Close the stream */ rtxStreamClose (&ctxt); /* Remember to release dynamic memory when done! */ rtFreeContext (&ctxt); }The only changes were the addition of the for (;;) loop and the call to rtxMemReset that was added at the bottom of the loop. This function resets the memory tracking parameters within the context to allow previously allocated memory to be reused for the next decode operation. Optionally, rtxMemFree can be called to release all memory. This will allow the loop to start again with no outstanding memory allocations for the next pass.
Objective Systems, Inc.55 Dowlin Forge RoadExton, Pennsylvania 19341 http://www.obj-sys.com Phone: (484) 875-9841 Toll-free: (877) 307-6855 (US only) Fax: (484) 875-9830 info@obj-sys.com |