Skip to content

Translate function pointers passed in variadic arguments#83

Merged
nunoplopes merged 5 commits into
Cpp2Rust:masterfrom
lucic71:vaarg-fn-pointer
May 12, 2026
Merged

Translate function pointers passed in variadic arguments#83
nunoplopes merged 5 commits into
Cpp2Rust:masterfrom
lucic71:vaarg-fn-pointer

Conversation

@lucic71
Copy link
Copy Markdown
Contributor

@lucic71 lucic71 commented May 12, 2026

In unsafe, the function pointer is first converted to void* when passed to a variadic function. Then, inside the variadic function, when calling va_arg(ap, fn_ptr), the function is first retrieved as void*, then transmuted to function pointer. The function pointer -calling variadic function-> void*, void* -va_arg(ap, fn_ptr)-> transmute<function pointer> is needed so that we don't add the unsafe transmute in libcc2rs.

In refcount, this dance is not needed. VaArg and VaArgGet are implemented for FnPtr safely.

Comment thread cpp2rust/converter/converter.cpp Outdated
if (expr->getType()->isFunctionPointerType()) {
StrCat("std::mem::transmute::<*mut ::libc::c_void", token::kComma);
Convert(expr->getType());
StrCat(">");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

'>'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

pub unsafe fn apply_unary_3(mut x: i32, args: &[VaArg]) -> i32 {
let mut ap: VaList = VaList::default();
ap = VaList::new(args);
let mut fn_: Option<unsafe fn(i32) -> i32> = std::mem::transmute::<
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is Option needed here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We translate functions pointers to Option<fn> in unsafe. Option is needed to encode nullability

@lucic71 lucic71 force-pushed the vaarg-fn-pointer branch from 21c6df6 to 127afb3 Compare May 12, 2026 20:10
@nunoplopes nunoplopes merged commit d15662f into Cpp2Rust:master May 12, 2026
9 checks passed
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