Rust wgpu C ABI

in C side i have uint32_t* arr = (uint32_t*)malloc(sizeof(uint32_t)*len) .

im trying to pass it to my rs func which gets mutmut u32 as para , and then Box the prev to Rust automatically and set new mem address to it , but i get free() invalid pointer error . i get that array from wgpu::BufferView

Your question is very hard to follow, but if you are allocating memory in C, and trying to free it in Rust, then it is very likely an UB. There is no guarantee that both C and Rust use the same allocator, and you cannot use different allocator to free memory, than the one you used to allocate it in the first place.

So either use Box and both allocate and free memory on the Rust side, or manage it in C and provide some sort of custom free function, that deallocates your array (you can then create a wrapper in Rust, that will call it in its Drop implementation).

3 Likes

Not by default, but it is possible to make that happen if you really need it.

1 Like

That is true. However funnily enough #[global_allocator] is usually used to change the default allocator, which on many platforms is the same as the system one. Still, I would not recommend to mix allocation and freeing across FFI. This is just begging for trouble.

No, it isn't, not really. From the docs of std::alloc::System:

However, it is not valid to mix use of the backing system allocator with System, as this implementation may include extra work, such as to serve alignment requests greater than the alignment provided directly by the backing system allocator.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.