TOP

ASN.1/C++ Program Examples

Applies to: ASN.1/C++ v7.3

Comprehensive Example

There are a number of examples located in the samples directory of your OSS ASN.1 Tools for C++ software installation. The best ones to start with are the encode and decode examples from the samples/basic directory. These are simple applications that demonstrate basic OSS ASN.1 Tools operations, including how to

  • Initialize the OSS API.
  • Use structures declared in the compiler-generated header file, specifically a SEQUENCE containing a VisibleString, an INTEGER, and a SEQUENCE OF type.
  • Encode and decode application messages.
  • Print out pre-encoded, encoded, and decoded data.
  • Free decoded data allocated by the decoder.

ASN.1 Specification: bcas.asn

BCAS DEFINITIONS ::= BEGIN

CareerEntry ::= SEQUENCE {
   from  INTEGER (0..MAX),
   to    INTEGER (0..MAX) OPTIONAL, -- absence means 'till now'
   team  VisibleString (SIZE (1..256))
}

BBCard ::= SEQUENCE {
    name VisibleString (SIZE (1..64)),
    age INTEGER (1..128),
    position VisibleString (SIZE (1..64)),
    career SEQUENCE OF CareerEntry
}

END

Generated Header File

Compile the ASN.1 specification above using the OSS ASN.1/C++ compiler:

asn1cpp bcas -ber

The following header file is generated:

/*************************************************************/
/* Copyright (C) 2015 OSS Nokalva, Inc.  All rights reserved.*/
/*************************************************************/

/* THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC.
 * AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC.
 * THIS FILE MAY NOT BE DISTRIBUTED.
 * THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED. */

/* Generated for: Open Systems Solutions */
/* Abstract syntax: bcas */
/* Created: Wed Apr 15 13:52:04 2015 */
/* ASN.1/C++ compiler version: 6.1 */
/* Code generated for runtime version 6.1 or later */
/* Compiler operating system: Windows X64 */
/* Compiler machine type: AMD64 */
/* Target operating system: Windows X64 */
/* Target machine type: AMD64 */
/* C++ compiler options required: None */
/* ASN.1 compiler options and file names specified:
 * -ber bcas
 */

#ifndef OSS_bcas
#define OSS_bcas

#include "oss.h"
#include "asn1.h"

/* Representation types */

class OSS_PUBLIC CareerEntry   /* SEQUENCE */
{
public:
    void * operator new(size_t size);
    void operator delete(void *ptr);

    typedef OSS_UINT32 from;
    typedef OSS_UINT32 to;
    typedef OssString team;

    CareerEntry();
    CareerEntry(const CareerEntry &);
    CareerEntry(from, to, const team &);
    CareerEntry(from, const team &);

    CareerEntry & operator = (const CareerEntry &);
    int operator == (const CareerEntry &) const;
    int operator != (const CareerEntry &) const;

    from & get_from();
    from get_from() const;
    void set_from(from);

    to *get_to();
    const to *get_to() const;
    void set_to(to);
    int to_is_present() const;
    void omit_to();

    team & get_team();
    const team & get_team() const;
    void set_team(const team &);
private:
    OSS_UINT32 bit_mask;
    from from_field;
    to to_field;
    team team_field;
};

class OSS_PUBLIC __seqof1 : public OssList  /* SEQUENCE OF */
{
public:
    typedef CareerEntry component;

    __seqof1();
    __seqof1(const __seqof1 &);
    ~__seqof1();

    __seqof1 & operator = (const __seqof1 &);
    int operator == (const __seqof1 &) const;
    int operator != (const __seqof1 &) const;

    component *at(OssIndex);
    const component *at(OssIndex) const;

    OssIndex prepend(const component & );
    OssIndex prepend(__seqof1 *);
    OssIndex insert_after(OssIndex, const component & );
    OssIndex insert_after(OssIndex, __seqof1 *);

    int remove_front();
    int remove_after(OssIndex);

    __seqof1 *extract_after(OssIndex, OssIndex);
};

class OSS_PUBLIC BBCard   /* SEQUENCE */
{
public:
    void * operator new(size_t size);
    void operator delete(void *ptr);

    typedef OssString name;
    typedef OSS_UINT32 age;
    typedef OssString position;
    typedef __seqof1 career;

    BBCard();
    BBCard(const BBCard &);
    BBCard(const name &, age, const position &, const career &);

    BBCard & operator = (const BBCard &);
    int operator == (const BBCard &) const;
    int operator != (const BBCard &) const;

    name & get_name();
    const name & get_name() const;
    void set_name(const name &);

    age & get_age();
    age get_age() const;
    void set_age(age);

    position & get_position();
    const position & get_position() const;
    void set_position(const position &);

    career & get_career();
    const career & get_career() const;
    void set_career(const career &);
private:
    name name_field;
    age age_field;
    position position_field;
    career career_field;
};

/* Universal PDU class */

class OSS_PUBLIC bcas_PDU : public UniversalPDU {
public:
    bcas_PDU();
    void set_BBCard(BBCard &);
    BBCard *get_BBCard() const;
#ifdef OSS_PREALLOCATED_BUFFER_DECODE_SUPPORTED
    void set_const_BBCard(const BBCard &);
    const BBCard *get_const_BBCard() const;
#endif
};

/* Specific PDU classes */

class OSS_PUBLIC BBCard_PDU : public ConcretePDU {
public:
    BBCard_PDU();
    void set_data(BBCard &);
    BBCard *get_data() const;
#ifdef OSS_PREALLOCATED_BUFFER_DECODE_SUPPORTED
    void set_const_data(const BBCard & d);
    const BBCard *get_const_data() const;
#endif
protected:
    OssTypeIndex get_index() const;
};

/* Control object class */

class OSS_PUBLIC bcas_Control : public OssControl {
public:
    bcas_Control();
    bcas_Control(const bcas_Control &);
};

#endif // OSS_bcas

NOTE: The predefined OSS_PREALLOCATED_BUFFER_DECODE_SUPPORTED macro reflects the current ASN.1/C++ runtime configuration; do not change it.

The ASN.1/C++ compiler also produces the bcas.cpp file that implements the methods declared in this header file and contains the encoder/decoder control table. The contents of this file are not listed here, but you can create and view it if you wish.

Sample Encoding Program

The following simple test program, basic/encode/encode.cpp, uses a header file similar to the one above for encoding:

/*************************************************************************/
/* Copyright (C) 2014 OSS Nokalva, Inc.  All rights reserved.                */
/*************************************************************************/
/* THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC.                    */
/* AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC.             */
/* THIS FILE MAY NOT BE DISTRIBUTED.                                         */
/* THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED.                              */
/*************************************************************************/
/*
 * FILE: @(#)encode.cpp	16.2 14/02/08
 */

/*
 * Encodes a sample baseball card using BCAS (Baseball Card Abstract Syntax).
 * with BER or PER (Basic or Packed Encoding Rules).
 */

#include "bcas.h"  /* compiler-generated header file */

/*
 * A class used to report ASN.1/C++ errors to the application. It is up to
 * the application programmer to decide which class to use for this purpose.
 * You may choose any different class (such as a descendant of the
 * std::exception class). You may also throw integer codes without defining
 * any class (however, we expect that most applications will use exception
 * classes).
 */

class ASN1Exception {
private:
    int code;
public:
    ASN1Exception(int asn1_code);
    ASN1Exception(const ASN1Exception & that);
    int get_code() const;
};

ASN1Exception::ASN1Exception(int asn1_code)
{
    code = asn1_code;
}

ASN1Exception::ASN1Exception(const ASN1Exception & that)
{
    code = that.code;
}

int ASN1Exception::get_code() const
{
    return code;
}

/*
 * The ASN.1/C++ error reporting function.
 */

void throw_error(int code)
{
    throw ASN1Exception(code);
}

/*
 * A helper function to create an object to be encoded.
 */
static BBCard *newCard(const char *name, int age, const char *position,
		int c_from, int c_to, const char *c_team);

/*
 * A helper function to print error message and textual description of
 * the code returned by any runtime API function.
 */
static int report_error(OssControl *ctl, const char *where, ASN1Exception &exc); 
			  
/*
 * Creates and encodes a baseball card PDU.
 */
int main()
{
    int code = 0;		/* return code */
    BBCard *card = NULL;	/* pointer to undecoded data */
    const char *where;		/* current operation -
				   used to print error messages if needed */

    /*
     * Handle ASN.1/C++ runtime errors with C++ exceptions.
     */
    asn1_set_error_handling(throw_error, TRUE);

    where = "initialization";
    try {
	bcas_Control ctl;	/* ASN.1/C++ control object */

	try {
	    EncodedBuffer encodedData;	/* encoded data */
	    BBCard_PDU pdu;		/* coding container for a BBCard value */
	    ossEncodingRules encRule;	/* default encoding rules */

	    where = "initial settings";

#ifdef RELAXED_MODE
	    /*
	     * Set relaxed mode.
	     */
	    ctl.setEncodingFlags(NOCONSTRAIN | RELAXBER | RELAXPER);
	    ctl.setDecodingFlags(NOCONSTRAIN | RELAXBER | RELAXPER);
#endif

	    ctl.setEncodingFlags(ctl.getEncodingFlags() | DEBUGPDU);
	    ctl.setDecodingFlags(ctl.getDecodingFlags() | DEBUGPDU);

	    /*
	     * Get the encoding rule, which is set currently.
	     */
	    encRule = ctl.getEncodingRules();

	    /*
	     * Create the instance of BBCard class to be encoded.
	     */
	    printf("Creating the PDU object to be encoded...");
	    where = "creating sample object";
	    card = newCard("Casey", 32, "left field",
			  2000, 2005, "New York Yankees");
	    printf(" success\n\n");

	    /*
	     * Set the data to the coding container.
	     */
	    pdu.set_data(*card);

	    /*
	     * Print the input to the encoder.
	     */
	    printf("The input to the encoder...\n\n");
	    where = "printing";
	    pdu.print(ctl);

	    /*
	     * Encode the object.
	     */
	    printf("\nThe encoder's trace messages (only for SOED)...\n\n");
	    where = "encoding";
	    pdu.encode(ctl, encodedData);
	    printf("\nPDU encoded successfully.\n");

	    /*
	     * Printing the encoded PDU.
	     */
	    printf("\n%s-Encoded PDU...\n\n",
		    encRule == OSS_BER ? "BER": "PER");
	    where = "printing";
	    encodedData.print_hex(ctl);

	} catch (ASN1Exception &exc) {
	    /*
	     * An error occurred during decoding.
	     */
	    code = report_error(&ctl, where, exc);
	}
    } catch (ASN1Exception &exc) {
	/*
	 * An error occurred during control object initialization.
	 */
	code = report_error(NULL, where, exc);
    } catch (...) {
	/*
	 * An unexpected exception is caught.
	 */
	printf("Unexpected exception caught.\n");
	code = -1;
    }

    /*
     * Delete the decoded data (if there are any).
     */
    delete card;

    /*
     * The encoder's output buffer was automatically allocated.
     * It should be deallocated by the encodedData's destructor,
     * so we don't need to delete it explicitly.
     */

    return code;
}

/*
 * FUNCTION	report_error() is a common interface for error handling.
 *
 * PARAMETERS
 *	ctl	OSS control object (NULL if the error occurred during
 *		initialization)
 *	where   the error origin
 *	exc     the exception object
 *
 * RETURNS	the value of the return code
 */
static int report_error(OssControl *ctl, const char *where, ASN1Exception &exc) 
{
    int code = exc.get_code();
    const char *msg;

    if (!code)
	/* success */
	return 0;

    printf("\nAn error happened\n  Error origin: %s\n  Error code: %d\n",
	     where, code);

    if (ctl) {
	msg = ctl->getErrorMsg();
    	if (msg && *msg)
	    printf("  Error text: '%s'\n", msg);
    }

    return code;
}

/*
 * FUNCTION	newCard() creates a Baseball card representation object
 *		with given component values. Input string values are copied.
 *
 * PARAMETERS
 *	name, age, position, c_from, c_to, c_team
 *		specify the components of the object to be created
 *
 * RETURNS	a pointer to the created object
 */
static BBCard *newCard(const char *name, int age, const char *position,
		   int c_from, int c_to, const char *c_team)
{
    BBCard::career career;

    /*
     * OssString has a constructor with one const char * argument,
     * so the implicit conversion takes place for name, position,
     * and team here.
     */
    CareerEntry entry(c_from, c_to, c_team);
    career.prepend(entry);
    return new BBCard(name, age, position, career);
}

Compile and link the generated code; follow the instructions in the samples/basic/encode/README.TXT file. Here is the full output of the executable file:

Creating the PDU object to be encoded... success

The input to the encoder...

value BBCard ::= 
{
  name "Casey",
  age 32,
  position "left field",
  career 
  {
    {
      from 2000,
      to 2005,
      team "New York Yankees"
    }
  }
}

The encoder's trace messages (only for SOED)...

BBCard SEQUENCE: tag = [UNIVERSAL 16] constructed; length = 52
  name VisibleString: tag = [UNIVERSAL 26] primitive; length = 5
    "Casey"
  age INTEGER: tag = [UNIVERSAL 2] primitive; length = 1
    32
  position VisibleString: tag = [UNIVERSAL 26] primitive; length = 10
    "left field"
  career SEQUENCE OF: tag = [UNIVERSAL 16] constructed; length = 28
    CareerEntry SEQUENCE: tag = [UNIVERSAL 16] constructed; length = 26
      from INTEGER: tag = [UNIVERSAL 2] primitive; length = 2
        2000
      to INTEGER: tag = [UNIVERSAL 2] primitive; length = 2
        2005
      team VisibleString: tag = [UNIVERSAL 26] primitive; length = 16
        "New York Yankees"

PDU encoded successfully.

BER-Encoded PDU...

30341A05 43617365 79020120 1A0A6C65 66742066 69656C64 301C301A 020207D0
020207D5 1A104E65 7720596F 726B2059 616E6B65 6573

Sample Decoding Program

Similarly, the following test program from the basic/decode directory illustrates decoding:

/**************************************************************************/
/* Copyright (C) 2014 OSS Nokalva, Inc.  All rights reserved.                */
/**************************************************************************/
/* THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC.                    */
/* AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC.             */
/* THIS FILE MAY NOT BE DISTRIBUTED.                                         */
/* THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED.                              */
/**************************************************************************/
/*
 * FILE: @(#)decode.cpp	16.2  14/02/08
 */

/*
 * Decodes BER and PER encoded baseball card using BCAS (Baseball Card
 * Abstract Syntax).
 */

#include "bcas.h"  /* compiler-generated header file */

/*
 * Input encodings.
 */

int berDataLen = 54;

int perDataLen = 43;

unsigned char berEncodedData[] = {
    0x30, 0x34, 0x1A, 0x05, 0x43, 0x61, 0x73, 0x65, 0x79, 0x02,
    0x01, 0x20, 0x1A, 0x0A, 0x6C, 0x65, 0x66, 0x74, 0x20, 0x66,
    0x69, 0x65, 0x6C, 0x64, 0x30, 0x1C, 0x30, 0x1A, 0x02, 0x02,
    0x07, 0xD0, 0x02, 0x02, 0x07, 0xD5, 0x1A, 0x10, 0x4E, 0x65,
    0x77, 0x20, 0x59, 0x6F, 0x72, 0x6B, 0x20, 0x59, 0x61, 0x6E,
    0x6B, 0x65, 0x65, 0x73
};

unsigned char perEncodedData[] = {
    0x10, 0x43, 0x61, 0x73, 0x65, 0x79, 0x3E, 0x48, 0x6C, 0x65,
    0x66, 0x74, 0x20, 0x66, 0x69, 0x65, 0x6C, 0x64, 0x01, 0x80,
    0x02, 0x07, 0xD0, 0x02, 0x07, 0xD5, 0x0F, 0x4E, 0x65, 0x77,
    0x20, 0x59, 0x6F, 0x72, 0x6B, 0x20, 0x59, 0x61, 0x6E, 0x6B,
    0x65, 0x65, 0x73
};

/*
 * A class used to report ASN.1/C++ errors to the application. It is up to
 * the application programmer to decide which class to use for this purpose.
 * You may choose any different class (such as a descendant of the
 * std::exception class). You may also throw integer codes without defining
 * any class (however, we expect that most applications will use exception
 * classes).
 */

class ASN1Exception {
private:
    int code;
public:
    ASN1Exception(int asn1_code);
    ASN1Exception(const ASN1Exception & that);
    int get_code() const;
};

ASN1Exception::ASN1Exception(int asn1_code)
{
    code = asn1_code;
}

ASN1Exception::ASN1Exception(const ASN1Exception & that)
{
    code = that.code;
}

int ASN1Exception::get_code() const
{
    return code;
}

/*
 * The ASN.1/C++ error reporting function.
 */

void throw_error(int code)
{
    throw ASN1Exception(code);
}

/*
 * printCard() accesses components of the decoded data and prints them.
 */
static void printCard(BBCard *card);

/*
 * A helper function to print error message and
 * textual description of the code returned by any runtime API function.
 */
static int report_error(OssControl *ctl, const char *where, ASN1Exception &exc);

/* Decodes PER and BER encoded cards */
int main()
{
    int code = 0;		/* return code */
    BBCard *cardPtr = NULL;	/* pointer to decoded data */

    /*
     * Handle ASN.1/C++ runtime errors with C++ exceptions.
     */
    asn1_set_error_handling(throw_error, TRUE);

    try {
	bcas_Control ctl;	/* ASN.1/C++ control object */

	try {
	    EncodedBuffer encodedData;	/* encoded data */
	    BBCard_PDU pdu;	/* coding container for a BBCard value */
	    int encRule;	/* default encoding rules */

#ifdef RELAXED_MODE
	    /*
	     * Set relaxed mode.
	     */
	    ctl.setEncodingFlags(NOCONSTRAIN | RELAXBER | RELAXPER);
	    ctl.setDecodingFlags(NOCONSTRAIN | RELAXBER | RELAXPER);
#endif

	    ctl.setEncodingFlags(ctl.getEncodingFlags() | DEBUGPDU);
	    ctl.setDecodingFlags(ctl.getDecodingFlags() | DEBUGPDU);

	    /*
	     * Do decoding. Note that API is the same for any encoding method.
	     * Get encoding rules which were specified on the ASN.1 compiler
	     * command line.
	     */
	    encRule = ctl.getEncodingRules();

	    /*
	     * Set the decoder's input.
	     */
	    if (encRule == OSS_BER) {
		encodedData.set_buffer(berDataLen, (char *)berEncodedData);
	    } else if (encRule == OSS_PER_ALIGNED) {
		encodedData.set_buffer(perDataLen, (char *)perEncodedData);
	    }

	    /*
	     * Print the encoded message.
	     */
	    printf("Printing the %s-encoded PDU...\n\n",
			encRule == OSS_BER ? "BER": "PER");
	    encodedData.print_hex(ctl);

	    /*
	     * Decode the encoded PDU whose encoding is in "encodedData".
	     * An exception will be thrown on any error.
	     */
	    printf("\nThe decoder's trace messages (only for SOED)...\n\n");
	    pdu.decode(ctl, encodedData);

	    /*
	     * Read and print the decoded data.
	     */
	    cardPtr = pdu.get_data();
	    printCard(cardPtr);
	} catch (ASN1Exception &exc) {
	    /*
	     * An error occurred during decoding.
	     */
	    code = report_error(&ctl, "decode", exc);
	}
    } catch (ASN1Exception &exc) {
	/*
	 * An error occurred during control object initialization.
	 */
	code = report_error(NULL, "initialization", exc);
    } catch (...) {
	/*
	 * An unexpected exception is caught.
	 */
	printf("Unexpected exception caught.\n");
	code = -1;
    }
    /*
     * Delete the decoded data (if there are any).
     */
    delete cardPtr;
    return code;
}

/*
 * FUNCTION	report_error() is a common interface for error handling.
 *
 * PARAMETERS
 *	ctl	OSS control object (NULL if the error occurred during
 *		initialization)
 *	where   the error origin
 *	exc     the exception object
 *
 * RETURNS	the value of the return code
 */
static int report_error(OssControl *ctl, const char *where, ASN1Exception &exc) 
{
    int code = exc.get_code();
    const char *msg;

    if (!code)
	/* success */
	return 0;

    printf("\nAn error happened\n  Error origin: %s\n  Error code: %d\n",
	     where, code);

    if (ctl) {
	msg = ctl->getErrorMsg();
    	if (msg && *msg)
	    printf("  Error text: '%s'\n", msg);
    }

    return code;
}

#define CURRENT_YEAR 2006

static void print_string(OssString &str);

/*
 * FUNCTION	printCard() prints contents of a Baseball card object in
 *		a human readable form. Besides that, it demonstrates how
 *		to access components of the decoded data. If you need no more
 *		than human readable printout of the decoded data, there is an
 *		easier way: it can be printed in the form of value notation
 *		using ASN1Handle::print() OSS ASN.1/C++ API method instead.
 * PARAMETERS
 *	card	the object to dump
 */
static void printCard(BBCard *card)
{
    int			count = 1;
    BBCard::career	*career;
    OssIndex		index;

    printf("\nBaseball card\n-------------\n");
    printf("  Name:      ");
    print_string(card->get_name());
    printf("\n  Age:       %d\n", card->get_age());
    printf("  Position:  ");
    print_string(card->get_position());
    printf("\n");

    career = &card->get_career();
    index = career->first();
    if (index != OSS_NOINDEX) {
	printf("  Career:\n");
	do {
	    CareerEntry *ce = career->at(index);

	    printf("    #%d: %d - %d: ",
			count,
			ce->get_from(),
			ce->to_is_present() ?
				*ce->get_to() :
				CURRENT_YEAR);
	    print_string(ce->get_team());
	    printf("\n");
	    count++;
	    index = career->next(index);
	} while (index != OSS_NOINDEX);
    }
}

/*
 * FUNCTION	print_string() prints contents of an OssString object in
 *		a human readable form (this may be done simpler by using
 *		the standard std::string class but we avoid STL in the
 *		sample).
 * PARAMETERS
 *	str	the object to dump
 */
static void print_string(OssString &str)
{
    const char *text = str.get_buffer();
    if (text) {
	for (unsigned int i = 0; i < str.length(); i++)
	    printf("%c", text[i]);
    } else
	printf("[unknown]");
}

Compile and link the generated code; follow the instructions in the samples/basic/decode/README.TXT file. Here is the full output of the executable file:

Printing the BER-encoded PDU...

30341A05 43617365 79020120 1A0A6C65 66742066 69656C64 301C301A 020207D0
020207D5 1A104E65 7720596F 726B2059 616E6B65 6573

The decoder's trace messages (only for SOED)...

BBCard SEQUENCE: tag = [UNIVERSAL 16] constructed; length = 52
  name VisibleString: tag = [UNIVERSAL 26] primitive; length = 5
    "Casey"
  age INTEGER: tag = [UNIVERSAL 2] primitive; length = 1
    32
  position VisibleString: tag = [UNIVERSAL 26] primitive; length = 10
    "left field"
  career SEQUENCE OF: tag = [UNIVERSAL 16] constructed; length = 28
    CareerEntry SEQUENCE: tag = [UNIVERSAL 16] constructed; length = 26
      from INTEGER: tag = [UNIVERSAL 2] primitive; length = 2
        2000
      to INTEGER: tag = [UNIVERSAL 2] primitive; length = 2
        2005
      team VisibleString: tag = [UNIVERSAL 26] primitive; length = 16
        "New York Yankees"

Baseball card
-------------
  Name:      Casey
  Age:       32
  Position:  left field
  Career:
    #1: 2000 - 2005: New York Yankees

Sample Compression Programs

Example Using the OssZlibCompressor Class

Following is an example using the OssZlibCompressor class. A more comprehensive and build-ready compression example is available in the samples/advanced/compression directory.

ASN.1 Specification: sample.asn
M DEFINITIONS ::= BEGIN
S ::= IA5String
s S ::= "Hello world! Hello world! Hello world! Hello world"
-- the value above will be compressed at runtime 
END
ASN.1 Compiler Command Line
asn1cpp sample -per -soed

Create a C++ source file with the following content:

#include "sample.h"

int main() {
    sample_Control ctl;
    int rc;
    unsigned long flag = OSS_RELAXED |  DEBUGPDU | 			AUTOMATIC_ENCDEC;

    ctl.setEncodingRules(OSS_PER_ALIGNED);
    ctl.setEncodingFlags(flag);
    ctl.setDecodingFlags(flag);

    // to use default compression level 
    OssCompressor *compressor = new OssZlibCompressor();
    ctl.setCompressor(compressor);

       S_PDU    pdu;
       S 	    mydata(s);
       EncodedBuffer eb;

       pdu.set_data(mydata);
       printf("Data to be encoded is: \n");
       pdu.print(ctl);

       // encode the data
rc = pdu.encode(ctl, eb);
if (rc) {
           printf("Encoding Failed with code: %d \n", rc);
       } else {
           printf("Data is Encoded Successfully....\n\n");
           ctl.printHex(eb.get_data(), eb.get_data_size());
       }

       printf("Now try to Decode the Encoded Data...\n\n");
       rc = pdu.decode(ctl, eb);
       if(rc) {
            printf("FAILED Decoding the encoded Data.\n");
       } else {
            printf("\nDecoded the EncodedData successfully.\n\n");
            pdu.print(ctl);
            pdu.free_data(ctl);
      }
	 delete compressor;
	 return rc;
}

Compile and link all the C++ source files using development tools appropriate for your target platform. Refer to samples/advanced/compression/makefile for details.

Sample Output:

Data to be encoded is:
value S ::= "Hello world! Hello world! Hello wor ..."

Data is Encoded Successfully....

3318789C 33F248CD C9C95728 CF2FCA49 5154208A 0300CA6E 11E6

Now try to Decode the Encoded Data...


Decoded the EncodedData successfully.

value S ::= "Hello world! Hello world! Hello wor ..."

↩Sample_Compression_Programs menu

Example Using a Custom Compressor Class

Using a custom compressor is illustrated by the BookCompressor class (see usercomp.h and usercomp.cpp in the samples/advanced/compression directory). This program is the same as the previous example that uses the OssZlibCompressor class, with the following differences:

The BookCompressor interface is declared in usercomp.h:

#include "asn1.h"
class BookCompressor : virtual public OssCompressor {
public:
    BookCompressor();
    int compress(void *inbuf, size_t inlen, void *outbuf, size_t *outlen);
    int decompress(void *inbuf, size_t inlen, void *outbuf, size_t *outlen);
    size_t compress_estimate(void *inbuf, size_t inlen);
private:
    unsigned char key;
};

The custom compressor methods are implemented in usercomp.cpp.

The custom class can be instantiated and used instead of OssZlibCompressor (see tbookusr.cpp):

OssCompressor *compressor = new BookCompressor;
ctl.setCompressor(compressor);

↩Sample_Compression_Programs menu


This documentation applies to release 7.3 and later of the OSS® ASN.1 Tools for C++.

Copyright © 2024 OSS Nokalva, Inc. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior permission of OSS Nokalva, Inc.
Every distributed copy of the OSS® ASN.1 Tools for C++ is associated with a specific license and related unique license number. That license determines, among other things, what functions of the OSS ASN.1 Tools for C++ are available to you.