← Runtimes
Runtimes

Calling across a foreign-function boundary

Strings, byte capacity and buffer ownership at a C ABI.

A foreign-function adapter must satisfy both the binary calling convention and the receiving library’s data and ownership contracts.

Outcome

Refuse text that C would read differently, measure capacity in UTF-8 bytes including the terminator, and release every foreign allocation exactly once on every path.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

ABI
The binary calling convention two compiled pieces agree on: how arguments, results and memory are passed.
C string
A sequence of bytes ending at the first zero byte.
NUL
The zero byte that ends a C string.
UTF-8
An encoding that represents each Unicode scalar value with one to four bytes. It is this SDK’s chosen encoding, not a rule imposed by every C ABI.
Double free
Releasing the same allocation twice, which is undefined behavior in C and can corrupt the allocator.
UTF-16 code unit
What JavaScript’s length counts; characters outside the basic plane take two.

What must cross the boundary

A foreign-function interface lets code call an implementation exposed through another language’s calling convention. The ABI defines how arguments and results cross that boundary. It does not by itself establish a string’s encoding, a buffer’s capacity or who must release an allocation; those rules come from the API.

This brings representation and lifetime decisions together. For a C-string API, distinguish the source string from its terminated byte buffer, measure capacity using the receiving API’s units, and keep the buffer alive while it is used. For a returned allocation, follow the documented ownership transfer and matching release operation. A managed or ownership-checked caller still needs an adapter that carries those obligations.

01Representation

Where does a C string end?

The warehouse service has a printer SDK whose label fields require NUL-terminated UTF-8 and whose rendered answers must be returned with its release function. A C ABI describes how the call is made; the SDK’s documentation supplies the text encoding, capacity and ownership rules. The adapter must preserve the address before it can enforce those rules.

The address arrives from checkout with an embedded NUL. Native strings can retain that data with their length. The SDK’s C-string scan ends at the first zero byte, so passing the bytes without validation would present only a prefix. A wrapper can refuse that conversion before the scan.

A shipping service receives an address line from a checkout API: Apt 4, a NUL, then Tower. Each program builds that line.

TextEncoder gives the UTF-8 bytes a C function would receive.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// An address line with an embedded NUL, and where a C reader would stop.

const line = "Apt 4\0Tower";
const bytes = new TextEncoder().encode(line);

console.log(`length: ${line.length}`);
console.log(`a C reader stops after ${bytes.indexOf(0)} bytes`);
What does the program print?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

Predict the source before revealing recorded results. TypeScript and Go model where a C-string scan stops without calling C. Rust uses the real standard-library CString conversion, but makes no foreign call. C++ uses the standard strlen interface; the source does not establish whether the build emitted an external call or inlined it.

02Capacity

How long is a name?

After refusing truncated addresses, the adapter must fit the remaining text into the SDK’s field. This SDK specifies UTF-8: an 8-byte field leaves at most 7 bytes for text and one for NUL. C itself does not select UTF-8, and a char* parameter alone does not specify an encoding.

Each program measures a recipient name a customer typed at checkout: Zoë followed by a smiling-face emoji.

A JavaScript string is a sequence of UTF-16 code units.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A recipient name from a checkout form, counted three ways.

const recipient = "Zoë🙂";

console.log(`length: ${recipient.length}`);
console.log(`code points: ${[...recipient].length}`);
console.log(`UTF-8 bytes: ${new TextEncoder().encode(recipient).length}`);
What are the three counts?

03Ownership

Who frees what a C library returns?

A line can fit the field and still be refused by the renderer, which reserves ^ for printer commands. In this SDK contract, both statuses return a new owned answer buffer. The caller must read or copy the answer before releasing it with the matching SDK function. A raw handle does not automatically acquire that cleanup behavior.

A label printer’s C SDK returns a pointer to a buffer it allocated and documents lib_free for releasing it. The caller is written in a garbage-collected or ownership-checked language. Who releases the buffer?

04Practice

Finish the shipping-label adapter

Complete the warehouse adapter through the same checks: preserve the decoded address while refusing interior NULs, enforce the SDK’s byte capacity, then manage answer ownership on both rendering statuses. The supplied SDK is an authored handle model in each native language; it performs no FFI call and allocates no unmanaged C buffer. Its live-buffer and double-release counters make the contract observable.

The shipping-label adapter

Pass the exact text, fit the field in bytes, then release every buffer.

  1. easy · R-FFI-V4-1 Pass the exact text
  2. medium · R-FFI-V4-2 Fit the field in bytes
  3. hard · R-FFI-V4-3 Release every buffer
In the frontend An HTML length limit does not size the SDK field Optional

The warehouse web form uses maxlength 8 for an SDK field with capacity 8 bytes including its terminator. Review the recipient shown here. Does the browser length limit establish that the name fits the SDK field?

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export default function Recipient() {
  return (
    <label>
      Recipient
      <input name="recipient" defaultValue="Zoë🙂" maxLength={8} />
    </label>
  );
}

The value has 5 UTF-16 code units, so maxlength 8 does not rule it out. The SDK instead needs 8 UTF-8 bytes plus one NUL byte, which exceeds its field. Apply the SDK’s documented conversion and capacity checks at the adapter boundary; the form attribute does not perform them.

Sources: HTML Standard: maxlength,Encoding Standard: TextEncoder.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.