04
Mon, Nov
6 New Articles

TechTip: Using C Functions, Part I

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

Using the C run-time library functions and setting up the prototypes for C functions is an easy way to use features available in the C language.

 

Note: This article is an excerpt from the book Functions in Free-Format RPG IV, published by MC Press.

 

Most RPG programmers don't know the C programming language and avoid technical articles or discussions that have anything to do with it. Until 1993, so did I. That year, I took some college classes in which C was the only language that could be used for assignments. I found that C was very different from RPG, but writing my own functions was very appealing. When I returned to an RPG environment in 1994, I assumed that I would not see any C programming again. In late 1994, however, IBM introduced RPG IV and ILE. At that point, integrating C functions with RPG IV programs became a possibility. 

Why Use C Functions?

The RPG IV language has a rich complement of op-codes and BIFs, so why would you consider accessing functions designed for the C language? The answer is that the C language gives you some functions you don't have in RPG, as well as functions that are more efficient than native RPG operations. Integrating C functions with your normal RPG code is easy, giving you the best of both languages.

 

To access a C function, you need to know the function's interface, including its name, number of parameters, parameter data types, and return value, if any.

 

To see why C functions might be useful to RPG programming, let's look at a few examples. Let's start with the C function Rand, which is used for random number generation. It has to be initialized with another function, called Srand, which "seeds" the random number generator. The notion of seeding is to set an initial value that is kept in the system somewhere. The Rand function cannot be used without first doing Srand, which must be run only once.

 

Here are few technical details to keep in mind when using these functions:

  • Srand requires an unsigned integer parameter, and there is no return value.
  • Rand has no parameters and returns an unsigned integer return value.

 You'll see examples that use both the Rand and Srand C functions later in this chapter.

 

Now, let's look at another C function, Strtok. This function is called string-token, and it is a string parser. For example, consider the string "The cat is gray." This string can be broken into separate tokens of "The," "cat," "is," and "gray" by using this function repetitively.

 

Here are few technical details to keep in mind when using this function:

  • Strtok requires a string parameter and a delimiter character.
  • The return value for Strtok is either a pointer to a token (a character string up to the first delimiter) or a null pointer.
  • It is common practice to use a blank as the delimiter, but other characters can be used.

 

You'll find an example that uses the Strtok function later in the chapter.

 

Now, let's consider a higher math function, Sin (the trigonometric function sine). Here are few technical details to keep in mind when using this function:

  • The Sin function has one parameter, the angle in radians.
  • It must be defined as a floating-point data type, either 4f or 8f.
  • The return value is also floating-point.

 

Review the IBM reference manual ILE C/C ++ Runtime Library Functions Reference for details on these or any other C functions you might be interested in. The document number is SC41-5607. This IBM publication can be viewed on the Web at the following link:

 

http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/books/sc415607.pdf

 

How C Functions Work with RPG IV

Using a C function within an RPG IV program requires the use of a prototype. The prototype defines to RPG IV the function's return value (if any) and the parameters needed for the function.

 

For example, consider this use of the Sin function:

 

dsin             pr             8f   extproc('sin')

d angle                         8f   value

 

The prototype name is made the same as the C function. The return value definition of 8f is specified, and the external procedure name is specified ('sin'). On the second line, the name angle is optional, since names on prototype parameters are not required. The 8f is the definition of the parameter, and the keyword value is used, since parameters in C functions expect parameter passing by value.

 

The call interface is the same as for any external procedure. The CallP operation can be used if no return value is needed. The implicit call (which works just like a BIF) is used when the C function has a return value. As you will see throughout this book, the implicit call is emphasized as a preferred method.

 

Let's add a few more lines of code to the example above:

 

dSinans          s             8f

dAngleF           s             8f

dAngleP           s              7p 2   Inz(1.0456)

/free

   AngleF = %float(AngleP);

   SinAns = sin(AngleF);

 

Three fields are defined:

  • Sinans will hold the answer.
  • AngleF is a floating-point work field.
  • AngleP is the input angle, in packed-decimal format.

 

The first new line of code uses the %float BIF to convert the packed-decimal AngleP field to floating-point and then assigns the value to the work field AngleF. The next line of code calls the function Sin implicitly, passing the work field AngleF as a parameter.

Random Numbers from C

One of the C functions that you might find useful is the random number function, mentioned earlier in this chapter. You'll see a detailed example using this function later, but for now, let me share the justification for using it in an application. The following situation occurred a couple of years ago:

 

I was working on an application to perform testing—giving an exam. The exam had four parts, with 10 questions in each part. The questions for each part came from a question pool, with 100 possible questions in the pool. The program needed to select, at random, 10 questions from each of the four associated question pools.

 

RPG IV does not have a random number function, but C does. Upon investigation, the Rand function in the C language was determined to be the proper choice. As explained earlier, Rand needs to be initialized by another C function, Srand.

 

The output from Rand is an integer between zero and 32,767. For the purposes of this application, I needed to scale that down to a range of zero to 99. A handy way to do this is to divide the return value by 100 (in this case) and use the remainder.

 

Because duplicate questions were not wanted in the exam, a check for a duplicate random number was needed, and duplicates discarded. The exam questions were stored in an array with indexes from one to 100, so the resulting random number needed to be incremented by one to match the RPG array index. Prototyping was needed for the two C functions, Rand and Srand, as follows:

 

D Set_random         PR                 Extproc('srand')

D     Seed                   10u 0

D Get_random          PR        10u 0     Extproc('rand')

 

Notice the use of the Extproc keyword and the C function name in lowercase. This is required. For the Set_random prototype, there is no return value (the "seed" is stored somewhere in the system), but there is an unsigned integer requirement as the parameter. It is best to make this parameter as random as possible. I have found that using the micro-seconds value of the current timestamp is fairly random.

 

Also, ILE needs to locate the procedures rand and srand, so a binding directory needs to be specified on the H control specification. The H control specification must be placed first in the source member. Here is an example:

 

 

H     Bnddir('QC2LE')

Random number setup can be done as follows:

 

 

  

D Seed               S          10u 0

D Index             S          10i 0

/free

Dou Seed <> 0;

     Seed = %subdt(%timestamp( ) : *MS);

     If Seed <> 0;

       Set_Random(Seed);

     Endif;

Enddo;

   // Obtaining the random number,

   // then scaling it to 0-99 is done as follows:

index = Get_Random( );     // index 0-32767

index = %rem(index:100);   // index 0-99

index += 1;                // index 1-100

 

The code above sets the seed (in the Dou group) and then uses the random number function to set an index. The index is used to access an array element from a question pool. Additional programming is needed to avoid duplicate indexes. The index is used to access a question from a question array.

 

Checking for duplicate random numbers and further processing of the application is not shown here.

 

Occasionally, the need for higher mathematical functions comes up. This might involve the use of trigonometric functions such as sine, cosine, or tangent. These are not available in RPG IV, but all of them are available in C.

 

The following trig functions are available in C:

 

  • Acos calculates the arc cosine.
  • Asin calculates the arc sine.
  • Atan calculates the arc tangent.
  • Atan2 is a variation of Atan for calculating the arc tangent.
  • Cos calculates the cosine.
  • Cosh calculates the hyperbolic cosine.
  • Sin calculates the sine.
  • Sinh calculates the hyperbolic sine.
  • Tan calculates the tangent.
  • Tanh calculates the hyperbolic tangent.

 

Using the C run-time library functions and setting up the prototypes for C functions is an easy way to use features available in the C language.

JIM MARTIN

Jim Martin holds a BS degree in mathematics and an MS in computer science. For 26 years, he was employed by IBM, where he wrote RPG applications for customers and worked in the programming laboratory as a programmer on portions of CPF and the OS/400 operating system. After leaving IBM, Jim took post-graduate work in computer science and performed RPG training. He is an IBM-certified RPG IV developer and author of multiple bestselling editions of Free-Format RPG IV, which, since the book's initial publication in 2005, have taught thousands of RPG IV programmers how to be successful with the free-format coding style.


MC Press books written by Jim Martin available now on the MC Press Bookstore.

Free-Format RPG IV: Third Edition Free-Format RPG IV: Third Edition
Improve productivity, readability, and program maintenance with the free-format style of programming in RPG IV.
List Price $59.95

Now On Sale

Free-Format RPG IV: Second Edition Free-Format RPG IV: Second Edition
>Make the transition from coding in fixed-format RPG to free format.
List Price $59.95

Now On Sale

Functions in Free-Format RPG IV Functions in Free-Format RPG IV
Here’s the ultimate guide to writing RPG IV programs with functions in the free-format style.
List Price $59.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

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: