Skip to content

Insert explicit byte-pointer casts for void pointer arithmetic#740

Merged
tannergooding merged 1 commit into
dotnet:mainfrom
tannergooding:tannergooding-fix-void-pointer-arithmetic
Jul 13, 2026
Merged

Insert explicit byte-pointer casts for void pointer arithmetic#740
tannergooding merged 1 commit into
dotnet:mainfrom
tannergooding:tannergooding-fix-void-pointer-arithmetic

Conversation

@tannergooding

Copy link
Copy Markdown
Member

C/C++ allow pointer arithmetic on void* (treating it as byte-sized), but C# does not and instead reports CS0242: The operation in question is undefined on void pointers. The generator emitted the arithmetic verbatim, producing uncompilable C# for a function body such as cpy(buf + size * size2, info, size).

This inserts an explicit (byte*) cast on any void* operand of an additive operator so the arithmetic is well-defined; byte* implicitly converts back to void* where the surrounding context requires it.

cpy(buf + size * size2, ...)  ->  cpy((byte*)buf + size * size2, ...)

The cast is applied to whichever operand is the void* (LHS or RHS), so buf - n, n + buf, and pointer difference a - b are all handled.


Compound assignment (+=/-=) and ++/-- on a void* lvalue are out of scope here -- those need a buf = (void*)((byte*)buf + n) rewrite rather than a localized operand cast, and are not exercised by the reported repro. Left as a follow-up.

Added a C regression test (CTest.VoidPointerArithmeticTest); C++ makes void* arithmetic a hard error, so the test uses C mode. No existing golden output changes -- the full ClangSharp.PInvokeGenerator.UnitTests suite passes (Failed: 0, Passed: 3725).

Fixes #296

C/C++ allow pointer arithmetic on `void*` (treating it as byte-sized),
but C# does not and instead reports CS0242. Emit an explicit `(byte*)`
cast on any `void*` operand of an additive operator so the arithmetic
is well-defined; `byte*` implicitly converts back to `void*` where the
surrounding context requires it.

Fixes dotnet#296

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergooding merged commit 2da53d0 into dotnet:main Jul 13, 2026
14 checks passed
@tannergooding
tannergooding deleted the tannergooding-fix-void-pointer-arithmetic branch July 13, 2026 14:58
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.

Error: arithmetic on a pointer to void

1 participant