Introduction
On z/OS, oftentimes valuable business logic is implemented in existing programs written in languages such as HLASM, COBOL and C. Modernization with Python therefore can entail rewriting existing interfaces in a way that they can be accessible from within Python themselves (for example via a C-language Python extension) or through a complete rewrite into Python code. However, when using IBM Open Enterprise SDK for Python this is not always necessary. You can leverage these existing assets rather than rewriting them in a way that makes them accessible to Python as they currently are, commonly with minimal or no changes to the original source. In this blog, we'll look at how to call new and existing compiled 64-bit XPLINK z/OS code from Python, including examples using C, COBOL, and High Level Assembler (HLASM).
As mentioned above, it is possible to write a Python extension module in C to interoperate with Python directly. However, when integrating with existing compiled code, this often results in an additional layer of mostly boilerplate wrapper code that must be developed, tested, and maintained. Over time, these wrappers can become yet another component requiring updates as interfaces evolve and Python APIs change. This provides an additional layer of complexity that can outweigh the benefits of modernization if careful consideration is not taken.
To simplify interoperability, Python includes the ctypes library, which allows Python applications to call functions exported from native shared libraries as though they were ordinary Python functions. Rather than requiring a custom extension module, ctypes can dynamically load a compiled library, define the expected argument and return types, and invoke functions directly from Python.
On z/OS this functionality is extended even further, as IBM Open Enterprise SDK for Python includes the ability to also call fetchable routes directly without the need to recompile existing code into a Dynamic Link Library (DLL). This enables Python applications to interact directly with existing z/OS components, including code written in C, C++, COBOL, PL/I, or HLASM, provided the target module exposes a compatible callable interface. As a result, existing business logic and system integrations can often be reused from Python with minimal additional infrastructure, making it easier to modernize applications while continuing to leverage proven z/OS assets.
Example 1.) A simple example
First, we can begin with a simple example: a DLL that exports a single function that takes two integers and returns their sum.
int add(int a, int b) {
return a + b;
}
I use IBM Open XL C/C++, however the DLL can be compiled with other compilers as well, so long as the function is exported (with IBM Open XL, -fvisibility=default ensures that all functions in the DLL are exported).
ibm-clang64 --shared -fvisibility=default -fzos-le-char-mode=ascii add.c -o add.so
Note: -fzos-le-char-mode=ascii is not required, however I/O from compiled modules remains unchanged and therefore when performing EBCDIC I/O, garbled text may appear interlaced with ASCII output from Python. It is best practice to carefully consider encoding behaviour when performing I/O from compiled modules called via ctypes.
Once we have our add.so available, to make use of it in Python requires the following workflow:
- Import
ctypes
- Create a
ctypes.CDLL object for our DLL
- Specify the return and argument types
After completing all three of those steps, we can treat add as if it were any normal Python function.
# import the library
import ctypes
# open the DLL
lib = ctypes.CDLL('./add.so')
# specify the return and argument types
lib.add.restype = ctypes.c_int
lib.add.argtypes = [ctypes.c_int, ctypes.c_int]
# call the function
x = lib.add(1, 2)
print(f"1 + 2 = {x}") # prints 1 + 2 = 3
This example demonstrates the basic workflow for calling compiled code with ctypes using a DLL; this workflow can be replicated for other functions as well.
Next we will make use of the IBM Open Enterprise SDK for Python's fetch service to call the same function when it is present in a load module.
Example 2.) Simple example with fetch
As before, we begin with the same add.c file, with the addition of a pragma to define the function as fetchable.
#pragma linkage(FETCHADD, fetchable)
int FETCHADD(int a, int b) {
return a + b;
}
This time instead of specifying our output as a DLL, we can output it to a Partitioned Data Set (PDS) which I have preallocated.
ibm-clang64 -fzos-le-char-mode=ascii add.c -o "//'WAUSTIN.CTYPES.DEMO(FETCHADD)'"
Ensure your PDS is now included in your STEPLIB, in this case via export STEPLIB=WAUSTIN.CTYPES.DEMO from the z/OS UNIX terminal.
The Python code also remains largely the same, however instead of ctypes.CDLL to open the library, we make use of ctypes.CFetch. ctypes.CFetch returns a _FuncPtr the same type of object retrieved in the previous example via lib.add.
The workflow otherwise remains unchanged: we simply specify the return and argument types of the function and invoke it as before as a normal Python function call.
import ctypes
# Load the fetchable module
fetched_add = ctypes.CFetch('FETCHADD')
# Specify return and argument types
fetched_add.fetchable_func.restype = ctypes.c_int
fetched_add.fetchable_func.argtypes = [ctypes.c_int, ctypes.c_int]
# Call the function
x = fetched_add(1, 2)
print(f"1 + 2 = {x}") # prints 1 + 2 = 3
The previous two demonstrations showed how to make calls to functions with basic types. However, most programs make use of more complicated datatypes like aggregates (e.g. C structs or COBOL records). The ctypes library provides a convenient way to specify and work with these types through Python's native class system, as shown in the next example.
Example 3.) Passing Structs/Aggregates
While simple integer parameters are useful for demonstrating the basics of ctypes, many real-world interfaces require passing records or parameter blocks. ctypes supports both pass-by-reference and pass-by-value aggregates. In this example, we pass a structure by value to a compiled C function and receive an updated structure as the return value.
Below is our simple program, containing a single structure definition and a function that accepts one structure argument and returns a structure argument, both by value.
typedef struct TaxInfo {
int income;
int tax;
} TaxInfo;
TaxInfo calculate_tax(TaxInfo info)
{
info.tax = info.income * 15 / 100;
return info;
}
ibm-clang64 \
--shared \
-fvisibility=default \
-fzos-le-char-mode=ascii \
tax.c \
-o tax.so
We compile our C program as before (in this example as a DLL; however a load module may also be used).
To work with structures using ctypes, we need to define a class that inherits from ctypes.Structure and define its members as an array of tuples in the _fields_ member.
import ctypes
class TaxInfo(ctypes.Structure):
# define structure fields
# ctypes automatically applies the correct
# alignment and padding rules for XPLINK
_fields_ = [
("income", ctypes.c_int),
("tax", ctypes.c_int),
]
lib = ctypes.CDLL("./tax.so")
# Function takes a TaxInfo by value
lib.calculate_tax.argtypes = [TaxInfo]
# Function returns a TaxInfo structure
lib.calculate_tax.restype = TaxInfo
info = TaxInfo(
income=50000,
tax=0
)
result = lib.calculate_tax(info)
print(
f"income={result.income} "
f"tax={result.tax}"
)
# output: income=50000 tax=7500
Now once we invoke our C language function call, we will receive back a TaxInfo object whose fields we can access as if they were normal member variables in a Python class.
ctypes, despite its name, can also be used for calling programs written in other languages. In the next example we will look at using ctypes to call a 64-bit XPLINK EBCDIC COBOL load module.
Example 4.) COBOL interop.
ctypes can be used to call 64-bit DLLs or fetchable routines written in other languages as well. The key consideration is that Python interoperates using C-compatible data types and calling conventions. As a result, calling COBOL from Python is conceptually similar to calling COBOL from C, with Python data types mapped to their equivalent C representations through ctypes.
IDENTIFICATION DIVISION.
PROGRAM-ID. CALCTAX.
DATA DIVISION.
LINKAGE SECTION.
01 LK-INCOME PIC S9(9) COMP-5.
01 LK-TAX PIC S9(9) COMP-5.
PROCEDURE DIVISION USING BY REFERENCE LK-INCOME
BY REFERENCE LK-TAX.
COMPUTE LK-TAX = LK-INCOME * 15 / 100
GOBACK.
END PROGRAM CALCTAX.
Note: The indentation is intentional.
I compile this code with cob2 (cob2 is the z/OS UNIX executable for the COBOL compiler; this is however not necessary and compilation can be done with JCL, TSO commands or other methods, I use UNIX System Services purely for consistency with the other examples). It is important to note that compilation must be done in 64-bit.
In the below example we specify c_int to pass a S9(9) COMP-5 value. More information on interlanguage calls including data type equivalence can be found at https://www.ibm.com/docs/en/zos/3.2.0?topic=cobol-data-equivalents.
cob2 -q64 -o "//'WAUSTIN.CTYPES.DEMO(CALCTAX)'" calctax.cbl
Once again, ensure your PDS is included in your STEPLIB, in our case via export STEPLIB=WAUSTIN.CTYPES.DEMO.
The Python code is similar to the previous examples; however this time we must specify that our arguments are pass-by-reference via ctypes.POINTER(ctypes.c_int) when defining the argument types and ctypes.byref when passing the arguments to the call.
import ctypes
# fetch the routine (equivalent COBOL may be called with CDLL if compiled into a DLL)
calctax = ctypes.CFetch('CALCTAX')
# we specify the return types as normal
# note: we do not have an explicit return — we use COBOL's pass-by-reference conventions for the return
calctax.fetchable_func.restype = None
# COBOL by default uses pass-by-reference, hence we use ctypes.POINTER to specify we are passing references
calctax.fetchable_func.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
# we create two variables to pass by reference
income_c = ctypes.c_int(50000)
tax = ctypes.c_int(0)
# use ctypes.byref to get a pointer to our existing variables
calctax(ctypes.byref(income_c), ctypes.byref(tax))
# <obj>.value allows us to access the value wrapped by the ctypes.c_int types
print(f"income={income_c.value} tax={tax.value}") # income=50000 tax=7500
When working with COBOL using ctypes, it is important to note that ctypes' default call model is based on C, therefore pass-by-value semantics are the default and pass-by-reference arguments must be explicitly specified. Further considerations must be made when dealing with interoperability where storage must explicitly remain below the bar. The next example will demonstrate enhancements made to IBM Open Enterprise SDK for Python's ctypes implementation to explicitly manage below-the-bar storage.
Example 5.) Below-the-Bar Storage, EBCDIC, and HLASM Interoperability
Many z/OS services are exposed through HLASM macros or callable assembler interfaces. While HLASM modules can be invoked from Python through custom extension modules, ctypes can also be used directly, which is often preferable when an assembler implementation already exists.
Adapting an example from the Easily Calling an Assembler Program from Python blog post, we can invoke the WTL (Write To Log) macro through a fetchable assembler routine.
The assembler routine accepts a single parameter: a pointer to the WTL parameter block, which we will specify as a Python class using ctypes.Structure and allocate below the bar using IBM Open Enterprise SDK for Python's ctypes.BelowBar.
Here we have our simple example of a 64-bit XPLINK HLASM routine that takes one argument a pointer to the parameter block.
WTLFUNC CELQPRLG DSASIZE=DSASZ
USING CEEDSAHP,4
* Parameter block pointer in R1 (XPLINK)
WTL MF=(E,(1))
* WTL RC returned in R15
* move to XPLINK return register
LR 3,15
CELQEPLG
CEEDSAHP CEEDSA SECTYPE=XPLINK
DSASZ EQU (*-CEEDSAHP_FIXED)
END WTLFUNC
Build step
ibm-clang64 -fno-integrated-as -fasm -Wa,--GOFF -Wa,--ASA \
-Wa,-ISYS1.MACLIB -Wa,-ISYS1.MODGEN -Wa,-ICEE.SCEEMAC \
-c wtlfunc.s -o wtlfunc.o
Link step
ibm-clang64 wtlfunc.o -Wl,-e,WTLFUNC -o "//'WAUSTIN.CTYPES.DEMO(WTLFUNC)'"
Note: These examples use ibm-clang64 for consistency with the previous examples and because it integrates well with z/OS UNIX System Services. Alternative methods that produce a 64-bit XPLINK-compatible module can be used instead.
This example introduces two z/OS-specific interoperability considerations:
- The WTL macro requires its parameter block to reside below the 2 GB bar.
- Character data must be supplied in EBCDIC.
IBM Open Enterprise SDK for Python provides facilities for addressing both requirements: str.encode(<encoding>) to produce strings with a particular encoding, and BelowBar to allocate memory below the 2 GB bar.
import ctypes
from ctypes import BelowBar, c_short, c_char
# WTL parameter block layout: 2-byte length, 2-byte flags, up to 126 bytes EBCDIC message
# we use _pack_ = 1 to ensure that the struct is not padded, as expected by the HLASM
class WTLParm(ctypes.Structure):
_pack_ = 1
_layout_ = 'ms'
_fields_ = [
('length', c_short),
('flags', c_short),
('msg', c_char * 126),
]
message = 'Hello from Python ctypes on z/OS!'
# convert our message into EBCDIC with code page 1047
ebcdic = message.encode('cp1047')
# WTL requires the parameter block to be below the 2 GB bar
bb = BelowBar(WTLParm)
bb.value.length = len(ebcdic) + 4 # total length includes the 4-byte header
bb.value.flags = 0
bb.value.msg = ebcdic.ljust(126, b'\x40') # pad with EBCDIC spaces
wtlfunc = ctypes.CFetch('WTLFUNC')
wtlfunc.fetchable_func.restype = ctypes.c_int
wtlfunc.fetchable_func.argtypes = [ctypes.c_void_p]
rc = wtlfunc(bb.addr)
print(f'WTL rc={rc}') # 0 = success, message written to operator log
When executed successfully, the routine issues the WTL macro and writes the supplied message to the z/OS operator log.
From Python's perspective, the assembler routine behaves no differently than the C and COBOL examples shown earlier. Once the appropriate argument and return types have been defined, ctypes can invoke HLASM routines directly, allowing existing assembler-based functionality to be reused from Python without introducing an additional extension layer.
Gotchas.
Throughout these examples there are a number of gotchas and common stumbling points one might encounter. I have included a comprehensive list below for easy reference.
- Python strings are UTF-8 by default. If the compiled code is EBCDIC, strings should be explicitly encoded using the
<string>.encode(<code page>) method. Similarly, returned EBCDIC strings can be converted to native Python UTF-8 strings using the <bytes>.decode(<encoding>) method.
- COBOL records have different alignment and padding rules than C structures. COBOL records are tightly packed. Similar to our HLASM example, setting
_pack_ = 1 and _layout_ = 'ms' will tell Python to adjust the rules. Padding can also be added manually if required by defining _fields_ appropriately.
- Ensure all components are 64-bit XPLINK. IBM Open Enterprise SDK for Python runs as a 64-bit XPLINK application. Any DLL or fetchable routine called via
ctypes must therefore also be compiled and linked as 64-bit XPLINK. A mismatch in AMODE or calling convention will typically result in failures ranging from unresolved entry points to immediate abends.
- Always define
argtypes and restype. While ctypes permits calls without explicitly defining argument and return types, doing so can lead to incorrect parameter conversion or ABENDs. It is recommended that every imported function have both argtypes and restype defined explicitly.
- Be aware of pass-by-value vs. pass-by-reference semantics. C interfaces typically use pass-by-value semantics by default, whereas COBOL interfaces commonly use pass-by-reference semantics. When interoperating with non-C languages, ensure that the Python
ctypes definition accurately reflects the expected calling convention using constructs such as ctypes.POINTER() and ctypes.byref() where required.
- Verify structure layout matches the compiled program. When exchanging aggregates between Python and compiled code, field order, alignment, packing, and overall structure size must match exactly. A mismatch can produce incorrect results even when the individual field definitions appear correct. It can be helpful to compare
ctypes.sizeof() results against the expected size from the compiled language.
- Below-the-bar storage requirements are interface-specific. Most interfaces can use normal Python-managed storage. However, some z/OS services, macros, and other interfaces require storage below the 2 GB bar. In those cases, use
ctypes.BelowBar when allocating buffers or parameter blocks passed to the routine.
Conclusion
The examples in this article demonstrate how Python applications running on z/OS can directly invoke existing 64-bit XPLINK code written in C, COBOL, HLASM, and other languages using ctypes. Whether accessing DLLs or fetchable routines, this approach allows developers to reuse mature and proven existing code with little or no modification to the original source.
Further Readings and References