分配数据以传递给FFI呼叫的正确方法是什么? [英] What is the right way to allocate data to pass to an FFI call?

查看:73
本文介绍了分配数据以传递给FFI呼叫的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

After discussing/learning about the correct way to call a FFI of the Windows-API from Rust, I played with it a little bit further and would like to double-check my understanding.

我有一个被两次调用的Windows API.在第一个调用中,它返回实际out参数所需的缓冲区大小.然后,第二次调用具有足够大小的缓冲区.我目前正在使用Vec作为此缓冲区的数据类型(请参见下面的示例).

I have a Windows API that is called twice. In the first call, it returns the size of the buffer that it will need for its actual out parameter. Then, it is called a second time with a buffer of sufficient size. I'm currently using a Vec as a datatype for this buffer (see example below).

代码有效,但我想知道这是否是正确的方法,还是更好地利用像alloc::heap::allocate这样的函数直接保留一些内存,然后使用transmute来转换结果FFI回来了.同样,我的代码可以正常工作,但是我试图在幕后找一些东西.

The code works but I'm wondering whether this is right way to do it or whether it would be better to utilize a function like alloc::heap::allocate to directly reserve some memory and then to use transmute to convert the result from the FFI back. Again, my code works but I'm trying to look a little bit behind the scenes.

extern crate advapi32;
extern crate winapi;
extern crate widestring;
use widestring::WideCString;
use std::io::Error as IOError;
use winapi::winnt;

fn main() {
    let mut lp_buffer: Vec<winnt::WCHAR> = Vec::new();
    let mut pcb_buffer: winapi::DWORD = 0;

    let rtrn_bool = unsafe {
        advapi32::GetUserNameW(lp_buffer.as_mut_ptr(),
                               &mut pcb_buffer )
    };

    if rtrn_bool == 0 {

        match IOError::last_os_error().raw_os_error() {
            Some(122) => {
                // Resizing the buffers sizes so that the data fits in after 2nd 
                lp_buffer.resize(pcb_buffer as usize, 0 as winnt::WCHAR);
            } // This error is to be expected
            Some(e) => panic!("Unknown OS error {}", e),
            None => panic!("That should not happen"),
        }
    }


    let rtrn_bool2 = unsafe {
        advapi32::GetUserNameW(lp_buffer.as_mut_ptr(), 
                               &mut pcb_buffer )
    };

    if rtrn_bool2 == 0 {
        match IOError::last_os_error().raw_os_error() {
            Some(e) => panic!("Unknown OS error {}", e),
            None => panic!("That should not happen"),
        }
    }

    let widestr: WideCString = unsafe { WideCString::from_ptr_str(lp_buffer.as_ptr()) };

    println!("The owner of the file is {:?}", widestr.to_string_lossy());
}

依赖项:

[dependencies]
advapi32-sys = "0.2"
winapi = "0.2"
widestring = "*"

推荐答案

理想情况下,您将使用 std::alloc::alloc ,因为您可以在布局中指定所需的对齐方式:

Ideally you would use std::alloc::alloc because you can then specify the desired alignment as part of the layout:

pub unsafe fn alloc(layout: Layout) -> *mut u8

主要缺点是,即使释放分配空间,您也需要知道对齐方式.

The main downside is that you need to know the alignment, even when you free the allocation.

使用Vec作为简单的分配机制是一种常见的做法,但是在使用它时要特别小心.

It's common practice to use a Vec as an easy allocation mechanism, but you need to be careful when using it as such.

  1. 请确保您的单位正确-"length"参数是 items 的数目还是 bytes 的数目?
  2. 如果将Vec分解为组成部分,则需要
  1. Make sure that your units are correct — is the "length" parameter the number of items or the number of bytes?
  2. If you dissolve the Vec into component parts, you need to
  1. 跟踪长度容量.有些人使用 shrink_to_fit 来确保这两个值是相同的.
  2. 避免穿越流-内存是由Rust分配的,必须必须由Rust释放.将其转换回要放置的Vec.
  1. track the length and the capacity. Some people use shrink_to_fit to ensure those two values are the same.
  2. Avoid crossing the streams - that memory was allocated by Rust and must be freed by Rust. Convert it back into a Vec to be dropped.

  • 请注意,空的Vec不会没有具有NULL指针!:

  • Beware that an empty Vec does not have a NULL pointer!:

    fn main() {
        let v: Vec<u8> = Vec::new();
        println!("{:p}", v.as_ptr());
        // => 0x1
    }
    


  • 对于您的特定情况,我建议您使用Veccapacity而不是自己跟踪第二个变量.您会注意到,您在第一次调用后忘记更新pcb_buffer,因此,我很确定代码将始终失败.这很烦人,因为它必须是可变的引用,因此您无法完全摆脱它.


    For your specific case, I might suggest using the capacity of the Vec instead of tracking the second variable yourself. You'll note that you forgot to update pcb_buffer after the first call, so I'm pretty sure that the code will always fail. It's annoying because it needs to be a mutable reference so you can't completely get away from it.

    此外,您可以extendVec rel ="nofollow noreferrer"> reserve 空间.

    Additionally, instead of extending the Vec, you could just reserve space.

    也无法保证第一次通话时所需的大小将与第二次通话时所需的大小相同.您可以进行某种循环,但随后您必须担心会发生无限循环.

    There's also no guarantee that the size required during the first call will be the same as the size required during the second call. You could do some kind of loop, but then you have to worry about an infinite loop happening.

    这篇关于分配数据以传递给FFI呼叫的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆