02
Sun, Jun
0 New Articles

Passing Variable-Length Fields Between RPG and CL

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Q: I'm having trouble passing a parameter between ILE CL and RPG IV. The RPG IV procedure being called accepts a variable-length field (the VARYING keyword is "use"). When I call the procedure as follows, I get an error that says the length of the field is incorrect. What am I doing wrong?

PGMA:      PGM                                                       
           DCL        VAR(&NAME) TYPE(*CHAR) LEN(20)                         
           CHGVAR     VAR(&NAME) VALUE('Stephen C.')       
           CALLPRC    PRC(MAKELOWER) PARM(&NAME)         
           /*  More stuff goes here... */              
           ENDPGM      

A: The problem you are having is that CL--unlike RPG IV--does not support variable-length fields. So when you pass a fixed-length character field, like the &NAME variable in your example, to an RPG IV procedure that expects a variable-length field, the field's length attribute is not included. So the RPG IV program thinks (and rightly so) that the data is corrupted.

In your example, a procedure call (the CALLPRC command) attempts to call an RPG IV procedure whose procedure interface is as follows:

.....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++
     D MakeLower       PI                  Export
     D   szText                     256A   Varying

This procedure accepts a parameter that is defined as a variable-length field. When the CALLPRC command is run, the procedure MakeLower is called and immediately fails, generating an "invalid field length" message. To explain why this is happening, let me first review variable-length fields.

Variable-Length Fields

When an RPG procedure accepts a variable-length field, it assumes the field will be formatted properly. Calling the procedure from RPG IV is easy, since you have to have a prototype and the compiler ensures that the data is formatted properly. But when you call a procedure (RPG or otherwise) from CL, no prototype is involved, and you have to ensure that the variable passed as a parameter is properly formatted.

Variable-length fields are unique in that their storage is prefixed with two extra bytes. This means that the field's internal storage size is two bytes longer than the field's declared length. So a 20-position field ends up using 22 bytes of storage. Those extra bytes are a two-byte binary value, or 5i0 in RPG IV syntax, that prefixes the data in the field and contains the current length of the field's contents. The two-byte prefix is automatically inserted and maintained by the RPG compiler. For example, if the field contained 'Bob Cozzi', its current length would be nine, and the two-byte prefix would contain X'0009'. The following figure illustrates the positions, character values, and hexadecimal symbols for a 20-position, variable-length field containing the value 'Bob Cozzi'.

prefix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
B
o
b

C
o
z
z
i











0
0
C
9
8
4
C
9
A
A
8
4
4
4
4
4
4
4
4
4
4
4
0
9
2
6
2
0
3
6
9
9
9
0
0
0
0
0
0
0
0
0
0
0

Figure 1: Hex dump of a variable-length field

The field's length attribute is hidden by RPG IV because of RPG's integrated support for variable-length fields. The field length is stored internally as a two-byte binary prefix. All RPG IV operation codes have been enhanced to accommodate variable-length fields. RPG opcodes automatically adjust the length prefix as appropriate.

The length of a variable-length field is, of course, identified when the field is declared. A field whose length is 20A, for example, is a simple 20-position character field. If you add the VARYING keyword, the field becomes a variable-length field with a length potential of 0 to 20. For example:

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++
     D Name            S             20A   Varying

The current length of a variable-length field may be set implicitly or explicitly. The current length is different from the declared length in that it is variable--from 0 up to the declared length. To set the current length of a variable-length field implicitly, copy a value to the field, as follows:

.....C..n01..............OpCode(ex)Extended-factor2++++++++++
     C                   eval      name = 'Bob Cozzi'

In this example, the string 'Bob Cozzi' is copied to the NAME field. The length of the NAME field is automatically adjusted to the length of the string copied to it by the EVAL opcode. This is an implicit field-length assignment. The EVAL opcode does not automatically trim off trailing blanks. If a fixed-length field is moved into a variable-length field, the variable-length field's current length is the same as the declared length of the fixed-length field. For example:

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++
     D First           S             10A   Inz('Bob')
     D Last            S             10A   Inz('Cozzi')
     D Name            S             20A   Varying
.....C..n01..............OpCode(ex)Extended-factor2++++++++++
     C                   eval      name = First + Last

In this example, the variable-length field NAME is assigned the concatenated value of the FIRST and LAST fields. Since FIRST and LAST fields are fixed-length, the value of NAME is as follows:

 *....v....1....v....2
  'Bob       Cozzi     '

Since trailing blanks are not automatically truncated, the current length of NAME ends up being set to 20. To get a more appropriate result, use the %TRIMR built-in function when assigning values to variable length fields, as follows:

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++
     D First           S             10A   Inz('Bob')
     D Last            S             10A   Inz('Cozzi')
     D Name            S             20A   Varying
.....C..n01..............OpCode(ex)Extended-factor2+++++++++++++
     C                   eval      name = %TrimR(First + Last)

The NAME field's current length is set to 15. Of course, you'll still have an issue of too many blanks between the first and last names, but that's another issue entirely.

To set a variable-length field's current length explicitly, use the %LEN built-in function, as follows:

.....C..n01..............OpCode(ex)Extended-factor2++++++++++
     C                   eval      %Len(name) = 3

In this example, the length of the variable-length field is adjusted to 3. A subsequent MOVE or EVAL of the NAME field's data to another field would return just the first three characters of the field. In this example, 'Bob' would be all that is returned.

To retrieve the current length of a variable-length field, use the %LEN built-in function on the right side of the operator. For example:

.....C..n01..............OpCode(ex)Extended-factor2++++++++++
     C                   eval      nLen = %Len(name)

This can be particularly useful in a DOx or FOR loop. The %LEN built-in function is very efficient because all it does is return the value stored in the two-byte binary prefix of the variable length field.

CL Support for Variable Length Fields

CL does not have integrated support for variable-length fields. In fact, it has no built-in support for this type of field at all. In order to properly pass a variable-length field from CL to RPG IV, the two-byte binary prefix must be managed by the CL module. This is accomplished by storing the length of the field's data in the first two positions in the field. Consequently, it's a good idea to increase the field length by two bytes.

In the example that follows, the field named &NAME was a 20-position character variable in this CL module. In order to accommodate the variable-length field parameter required by the MAKELOWER routine, I've added two bytes to the field's length. The field's length is now 22 (line 2 in Figure 2).

VARCHAR2:  PGM                                                       
           DCL        VAR(&NAME) TYPE(*CHAR) LEN(22)                         
           CHGVAR     VAR(%BIN(&NAME 1 2)) VALUE(9)                  
           CHGVAR     VAR(%SST(&NAME 3 20)) VALUE('Bob Cozzi')       
           CALLPRC    PRC(MAKELOWER) PARM(&NAME)                       
           ENDPGM      

Figure 2: CL module correctly calling an RPG IV procedure

In order to embed a two-byte, binary-length prefix into the &NAME variable, the %BIN CL built-in function is used (see line 3 in Figure 2). The syntax of %BIN is similar to %SST in that it accepts a field name, a starting position, and a length. The length indicates the number of characters that will be modified or extracted as a binary (i.e., integer) value. Once the length (9 in this example) is embedded in the two-byte prefix, you can copy the data into the field. But you cannot copy it into position 1 and 2 of the field because that would overwrite the field's length. By using the %SST (substring) built-in function (line 4 in Figure 2), you bypass the two-byte, binary-length prefix and copy the data into the field starting in position 3.

When the MAKELOWER procedure is called (line 5 in Figure 2), the variable &NAME becomes a properly formatted variable-length field and should pass through properly.

The source code for the MAKELOWER procedure in RPG IV is listed in Figure 3.

     P MakeLower       B
.....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++
     D MakeLower       PI                  Export
     D   szText                     256A   Varying

     D UPPER           C                   'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     D lower           C                   'abcdefghijklmnopqrstuvwxyz'
     D nLen            S              5I 0

.....C*Rn01..............OpCode(ex)Extended-factor2++++++++++++++
     C                   eval      nLen = %Len(szText)
     C     UPPER:lower   XLATE     szText        szText
     C                   return
     P MakeLower       E

Figure 3: RPG IV source for the MAKELOWER procedure

Upon return from the call to MAKELOWER, the CL program should inspect the two-byte binary prefix and figure out how long the data is in the field. Figure 4 illustrates this technique. Lines 8 and 9 extract the current length of the variable-length field and then use that length with the %SST built-in function to extract the modified data from the &NAME field.

VARCHAR4:  PGM                                                       
           DCL        VAR(&NAME) TYPE(*CHAR) LEN(22)                         
           DCL        VAR(&LNAME) TYPE(*CHAR) LEN(20)                         
           DCL        VAR(&LEN) TYPE(*DEC) LEN(5 0)                         
           CHGVAR     VAR(%BIN(&NAME 1 2)) VALUE(9)                  
           CHGVAR     VAR(%SST(&NAME 3 20)) VALUE('Bob Cozzi')       
           CALLPRC    PRC(MAKELOWER) PARM(&NAME)                       
           CHGVAR     VAR(&LEN) VALUE(%BIN(&NAME 1 2))                  
           CHGVAR     VAR(&LNAME) VALUE(%SST(&NAME 3 &LEN)) 
           ENDPGM      

Figure 4: Modified CL source to extract a variable-length field's current length

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: