Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use tuple style struct in C binding #5167

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bindings/c/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
A simple read and write example

```C
#include "assert.h"
#include <assert.h>
#include <stdio.h>
#include "opendal.h"
#include "stdio.h"

int main()
{
Expand All @@ -37,7 +37,7 @@ int main()
assert(read_bytes->len == 24);

/* Lets print it out */
for (int i = 0; i < 24; ++i) {
for (size_t i = 0; i < 24; ++i) {
printf("%c", read_bytes->data[i]);
}
printf("\n");
Expand Down
2 changes: 1 addition & 1 deletion bindings/c/include/opendal.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ typedef struct opendal_entry {
* The pointer to the opendal::Entry in the Rust code.
* Only touch this on judging whether it is NULL.
*/
void *inner;
void *_0;
} opendal_entry;

/**
Expand Down
14 changes: 6 additions & 8 deletions bindings/c/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,24 @@ use ::opendal as core;
/// @see opendal_list_entry_path()
/// @see opendal_list_entry_name()
#[repr(C)]
pub struct opendal_entry {
pub struct opendal_entry(
/// The pointer to the opendal::Entry in the Rust code.
/// Only touch this on judging whether it is NULL.
inner: *mut c_void,
}
*mut c_void,
);

impl opendal_entry {
fn deref(&self) -> &core::Entry {
// Safety: the inner should never be null once constructed
// The use-after-free is undefined behavior
unsafe { &*(self.inner as *mut core::Entry) }
unsafe { &*(self.0 as *mut core::Entry) }
}
}

impl opendal_entry {
/// Used to convert the Rust type into C type
pub(crate) fn new(entry: core::Entry) -> Self {
Self {
inner: Box::into_raw(Box::new(entry)) as _,
}
Self(Box::into_raw(Box::new(entry)) as _)
}

/// \brief Path of entry.
Expand Down Expand Up @@ -79,7 +77,7 @@ impl opendal_entry {
#[no_mangle]
pub unsafe extern "C" fn opendal_entry_free(ptr: *mut opendal_entry) {
if !ptr.is_null() {
drop(Box::from_raw((*ptr).inner as *mut core::Entry));
drop(Box::from_raw((*ptr).0 as *mut core::Entry));
drop(Box::from_raw(ptr));
}
}
Expand Down
Loading