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 */ main () { ASN1TAG msgtag; int msglen, stat; ASN1CTXT ctxt; PersonnelRecord employee; const char* filename = "message.dat" /* Step 1: Initialize a context variable for decoding */ if (rtInitContext (&ctxt) != ASN_OK) { /* initialization failed, could be a license problem */ printf ("context initialization failed (check license)\n"); return -1; } rtStreamBufInit (&ctxt); /* Step 2: Open the input stream to read data */ stat = rtStreamFileOpen (&ctxt, filename, OSRTSTRMF_INPUT); if (stat != ASN_OK) { xu_perror (&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).. */ stat = rtStreamBufMark (&ctxt, 32); if (stat != ASN_OK) { xu_perror (&ctxt); return stat; } stat = berDecStrmTagAndLen (&ctxt, &msgtag, &msglen); if (stat != ASN_OK) { xu_perror (&ctxt); return stat; }if (msgtag == TV_PersonnelRecord) { stat = rtStreamBufReset (&ctxt); if (stat != ASN_OK) { xu_perror (&ctxt); return stat; } /* 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 == ASN_OK) { process received data in `employee' variable.. } else error processing... } else check for other known message types.. /* Need to reset all memory for next iteration */ rtMemReset (&ctxt); } /* end of loop */ /* Step 6: Close the stream */ rtStreamBufClose (&ctxt); /* Remember to release dynamic memory when done! */ rtFreeContext (&ctxt); }The only changes were the addition of the for (;;) loop and the call to rtMemReset 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, rtMemFree 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.102 Pickering Way, Suite #506Exton, 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 |