Insert explicit byte-pointer casts for void pointer arithmetic#740
Merged
tannergooding merged 1 commit intoJul 13, 2026
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
C/C++ allow pointer arithmetic on
void*(treating it as byte-sized), but C# does not and instead reportsCS0242: The operation in question is undefined on void pointers. The generator emitted the arithmetic verbatim, producing uncompilable C# for a function body such ascpy(buf + size * size2, info, size).This inserts an explicit
(byte*)cast on anyvoid*operand of an additive operator so the arithmetic is well-defined;byte*implicitly converts back tovoid*where the surrounding context requires it.The cast is applied to whichever operand is the
void*(LHS or RHS), sobuf - n,n + buf, and pointer differencea - bare all handled.Compound assignment (
+=/-=) and++/--on avoid*lvalue are out of scope here -- those need abuf = (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++ makesvoid*arithmetic a hard error, so the test uses C mode. No existing golden output changes -- the fullClangSharp.PInvokeGenerator.UnitTestssuite passes (Failed: 0, Passed: 3725).Fixes #296