Skip to content

Rewrite FFI structs section with a runnable example#3107

Open
lunadogbot wants to merge 2 commits into
denoland:mainfrom
lunadogbot:docs-improve/ffi-struct-example
Open

Rewrite FFI structs section with a runnable example#3107
lunadogbot wants to merge 2 commits into
denoland:mainfrom
lunadogbot:docs-improve/ffi-struct-example

Conversation

@lunadogbot
Copy link
Copy Markdown
Contributor

The "Working with structs" section in runtime/fundamentals/ffi.md had an
example that did not run: it defined the struct as { fields: { x: "f64", y: "f64" } } (the supported-types table on the same page documents { struct: [...] } as an array of field types), called new Deno.UnsafePointer(...) as
a constructor, and built struct values by passing BigInt(Float64Array.of(1.0) .buffer) — which throws TypeError: Cannot convert [object ArrayBuffer] to a BigInt. A reader copying it would hit that error before getting anywhere.

This PR replaces the section with a complete walkthrough: a small C Point
library, the cc command to build it, and a Deno script that calls
distance and midpoint using { struct: ["f64", "f64"] }, passing values
as a Uint8Array view of a Float64Array and decoding the returned struct
back through a Float64Array. The observed console.log output is shown
verbatim. A short "things to keep in mind" list calls out padding, positional
fields, and how returned structs come back as bytes.

Verified by building libpoint.so with cc 13.3.0 and running the exact
script from the page inside denoland/deno:latest (2.7.14 — no :canary
tag is currently published) with --allow-ffi. Output matched: distance = 5, midpoint = { x: 2.5, y: 4 }. deno fmt was run on the file. The
section's only change is to itself; no other sections were touched.

Closes bartlomieju/orchid-inbox#46

@lunadogbot
Copy link
Copy Markdown
Contributor Author

@bartlomieju ready for review when you have a moment.

Copy link
Copy Markdown
Member

@bartlomieju bartlomieju left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work, please remove em dashes from prose

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants