google / google/autocxx

Possible way to support field accesses with offset known only by C++

Open
#21 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
2.6k
Forks
175
PR merge metrics
No merged PRs in 30d

Description

Follow-up to https://github.com/google/autocxx/issues/19#issuecomment-706634698. Here is a proof of concept ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8d66743adb1841497ec14d6809b68092)).

```rust
// Suppose we have no idea what the true size/alignment of std::string is but
// want a Rust struct which behaves like:
//
// struct S {
// std::string i;
// std::string j;
// uint32_t k;
// };

use std::fmt::{self, Debug};

#[repr(C)]
pub struct CxxString([u8; 0]);

#[repr(C)]
pub struct S {
pub i: CxxString,
_rest: (),
}

impl Debug for S {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_struct("S")
.field("i", &self.i)
.field("j", &self.j)
.field("k", &self.k)
.finish()
}
}

#[repr(C)]
pub struct _Has_j {
pub j: CxxString,
_rest: (),
}

#[repr(C)]
pub struct _Has_k {
pub k: u32,
_rest: (),
}

impl std::ops::Deref for S {
type Target = _Has_j;
fn deref(&self) -> &Self::Target {
unsafe {
&*(self as *const S)
.cast::()
.offset(foreign::_S_i_to_j())
.cast::<_Has_j>()
}
}
}

impl std::ops::Deref for _Has_j {
type Target = _Has_k;
fn deref(&self) -> &Self::Target {
unsafe {
&*(self as *const _Has_j)
.cast::()
.offset(foreign::_S_j_to_k())
.cast::<_Has_k>()
}
}
}

impl Debug for CxxString {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("\"TODO\"")
}
}

// Implemented in C++.
mod foreign {
pub extern "C" fn _S_i_to_j() -> isize {
// return offsetof(S, j) - offsetof(S, i);
32
}
pub extern "C" fn _S_j_to_k() -> isize {
// return offsetof(S, k) - offsetof(S, j);
32
}
}

pub fn print_k_get_j(s: &S) -> &CxxString {
println!("{}", s.k);
return &s.j;
}
```

Contributor guide

Open the contributing guide

Research direction

Start with the linked issue 19 comment and reproduce the proof of concept in the Rust playground. Examine the C++ implementations of the foreign offset functions and the Rust field-access pattern shown here. Done means establishing whether autocxx can support field accesses whose offsets are known only by C++.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.