rust - 我应该在 FFI 上下文中传递可变引用还是转移变量的所有权?

标签 rust ffi c-strings widestring

我有一个程序通过 C FFI(通过 winapi-rs)使用 Windows API。其中一个函数需要一个指向字符串指针的指针作为输出参数。该函数会将其结果存储到此字符串中。我为此字符串使用类型为 WideCString 的变量。

我可以“只是”将一个可变引用传递给一个字符串引用到这个函数中(在一个不安全的 block 内)还是我应该使用像 .into_raw() 这样的功能>.from_raw() 也将变量的所有权移至 C 函数?

两个版本都可以编译和工作,但我想知道我是否购买了直接方式的任何缺点。

以下是我使用 .into_raw.from_raw 的代码中的相关行。

let mut widestr: WideCString = WideCString::from_str("test").unwrap(); //this is the string where the result should be stored
let mut security_descriptor_ptr: winnt::LPWSTR = widestr.into_raw();

let rtrn3 = unsafe {
    advapi32::ConvertSecurityDescriptorToStringSecurityDescriptorW(sd_buffer.as_mut_ptr() as *mut std::os::raw::c_void,
                                    1, 
                                    winnt::DACL_SECURITY_INFORMATION,
                                    &mut security_descriptor_ptr,
                                        ptr::null_mut())

};

if rtrn3 == 0 {
    match IOError::last_os_error().raw_os_error() {
        Some(1008) => println!("Need to fix this errror in get_acl_of_file."), // Do nothing. No idea, why this error occurs
        Some(e) => panic!("Unknown OS error in get_acl_of_file {}", e),
        None => panic!("That should not happen in get_acl_of_file!"),
    }
}

let mut rtr: WideCString = unsafe{WideCString::from_raw(security_descriptor_ptr)};

description of this parameter in MSDN说:

A pointer to a variable that receives a pointer to a null-terminated security descriptor string. For a description of the string format, see Security Descriptor String Format. To free the returned buffer, call the LocalFree function.

我期待函数改变变量的值。根据定义,这不意味着我要转移所有权吗?

最佳答案

I am expecting the function to change the value of the variable. Doesn't that - per definition - mean that I'm moving ownership?

没有。考虑所有权的一个关键方法是:当你用完它时,谁负责销毁值(value)。

有能力的 C API(Microsoft 通常属于此类)文档 预期的所有权规则,尽管有时这些词是间接的或假设了某种程度的外部知识。这个特殊的功能说:

To free the returned buffer, call the LocalFree function.

这意味着 ConvertSecurityDescriptorToStringSecurityDescriptorW 将执行某种分配并将其返回给用户。查看函数声明,您还可以看到他们将该参数记录为“out”参数:

_Out_ LPTSTR               *StringSecurityDescriptor,

为什么要这样做?因为调用者不知道分配多少内存来存储字符串1!

通常,您会将对未初始化内存 的引用传递给函数,然后该函数必须为您初始化它。

这可以编译,但您没有提供足够的上下文来实际调用它,所以谁知道它是否有效:

extern crate advapi32;
extern crate winapi;
extern crate widestring;

use std::{mem, ptr, io};
use winapi::{winnt, PSECURITY_DESCRIPTOR};
use widestring::WideCString;

fn foo(sd_buffer: PSECURITY_DESCRIPTOR) -> WideCString {
    let mut security_descriptor = unsafe { mem::uninitialized() };

    let retval = unsafe {
        advapi32::ConvertSecurityDescriptorToStringSecurityDescriptorW(
            sd_buffer,
            1,
            winnt::DACL_SECURITY_INFORMATION,
            &mut security_descriptor,
            ptr::null_mut()
        )
    };

    if retval == 0 {
        match io::Error::last_os_error().raw_os_error() {
            Some(1008) => println!("Need to fix this errror in get_acl_of_file."), // Do nothing. No idea, why this error occurs
            Some(e) => panic!("Unknown OS error in get_acl_of_file {}", e),
            None => panic!("That should not happen in get_acl_of_file!"),
        }
    }

    unsafe { WideCString::from_raw(security_descriptor) }
}

fn main() {
    let x = foo(ptr::null_mut());
    println!("{:?}", x);
}
[dependencies]
winapi = { git = "https://github.com/nils-tekampe/winapi-rs/", rev = "1bb62e2c22d0f5833cfa9eec1db2c9cfc2a4a303" }
advapi32-sys = { git = "https://github.com/nils-tekampe/winapi-rs/", rev = "1bb62e2c22d0f5833cfa9eec1db2c9cfc2a4a303" }
widestring = "*"

直接回答您的问题:

Can I "just" pass in a mutable ref to a ref to a string into this function (inside an unsafe block) or should I rather use a functionality like .into_raw() and .from_raw() that also moves the ownership of the variable to the C function?

都没有。该函数不希望您将指向字符串的指针传递给它,它希望您将指针传递给可以放置字符串的位置。

I also just realized after your explanation that (as far as I understood it) in my example, the widestr variable never gets overwritten by the C function. It overwrites the reference to it but not the data itself.

WideCString::from_str("test") 分配的内存很可能完全泄漏,因为在函数调用后没有任何内容引用该指针。

Is this a general rule that a C (WinAPI) function will always allocate the buffer by itself (if not following the two step approach where it first returns the size)?

我不相信 C API 之间或 C API 的内部有任何通用规则。尤其是在像微软这样拥有如此多 API 面的大公司。您需要阅读每种方法的文档。这是持续拖累的一部分,可以使编写 C 感觉像一个口号。

it somehow feels odd for me to hand over uninitialized memory to such a function.

是的,因为并不能真正保证函数会初始化它。事实上,在失败的情况下初始化它会很浪费,所以它可能不会。这是 Rust 似乎有更好的解决方案的另一件事。


请注意,在调用诸如 last_os_error 之类的东西之前,您不应该进行函数调用(例如 println!);这些函数调用可能会更改最后一个错误的值!


1 其他 Windows API 实际上需要一个多步骤过程 - 您使用 NULL 调用该函数,它返回您需要的字节数分配,然后你再调用它

关于rust - 我应该在 FFI 上下文中传递可变引用还是转移变量的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534712/

相关文章:

rust - 是否可以分解一段包含 return 语句的函数?

ruby - 如何使用 ruby​​ ffi 在 ruby​​ gem 中调用自定义 C 代码

使用 FFI 和 C 函数在 ruby​​ 中创建动态数组类

c - 为什么下面的代码会产生段错误

string - Swift 快速低级 String lastIndexOf

Rust:错误 [E0495]:由于需求冲突,无法推断出 autoref 的适当生命周期

rust - 为什么借用的字符串字面量可以通过伪造生命周期比其所有者长寿?

rust - 如何连接到 Rust 中的 systemd D-Bus org.freedesktop.timedate1 端点?

c - Erlang 产生大量 C 进程

C 实现可以使用长度前缀字符串 "under the hood"吗?