小编Del*_*ore的帖子

链接到使用MSVC编译的静态lib

我正试图在Windows上针对Rust库链接一个简单的C lib

我的lib是.h

extern "C" {
    void say_hello(const char* s);
}
Run Code Online (Sandbox Code Playgroud)

的.cpp

#include <stdio.h>

void say_hello(const char* s) {
    printf("hello world");
}
Run Code Online (Sandbox Code Playgroud)

我的Rust文件

#[link(name="CDbax", kind="static")]
extern "C" {
    fn say_hello(s: *const libc::c_char) -> () ;
}
Run Code Online (Sandbox Code Playgroud)

通过给出其中一个数据符号的错误来链接失败

error: linking with `gcc` failed: exit code: 1
note: "gcc" "-Wl,--enable-long-section-names" "-fno-use-linker-plugin" "-Wl,--nxcompat" "-Wl,--large-address-aware" "-shared-libgcc" "-L" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib" "e:\Rust\DBTools\DBAnalytics\target\debug\DBAnalytics.o" "-o" "e:\Rust\DBTools\DBAnalytics\target\debug\DBAnalytics.dll" "e:\Rust\DBTools\DBAnalytics\target\debug\DBAnalytics.metadata.o" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\libstd-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\libcollections-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\librustc_unicode-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\librand-11582ce5.rlib" "C:\Program Files (x86)\Rust …
Run Code Online (Sandbox Code Playgroud)

dll rust

5
推荐指数
1
解决办法
1200
查看次数

结构体中枚举的生命周期参数

我不明白为什么这种类型的结构会出现错误

enum Cell <'a> {
    Str(&'a str),
    Double(&'a f32),
}

struct MyCellRep<'a> {
    value: &'a Cell,
    ptr: *const u8,
}

impl MyCellRep{
    fn new_from_str(s: &str) {
        MyCellRep { value: Cell::Str(&s), ptr: new_sCell(CString::new(&s)) }
    }

    fn new_from_double(d: &f32) {
        MyCellRep { value: Cell::Double(&d), ptr: new_dCell(&d) }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误

14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14     value : & 'a Cell ,
Run Code Online (Sandbox Code Playgroud)

所以我也尝试过

struct MyCellRep<'a> {
    value: &'a Cell + 'a,
    ptr: *const u8,
} …
Run Code Online (Sandbox Code Playgroud)

enums struct lifetime rust

5
推荐指数
1
解决办法
7466
查看次数

使用fmt :: Display进行打印

我正在尝试使用fmt :: Display打印枚举(或结构).虽然代码编译并获取显示方法,但它不会打印该值.

pub enum TestEnum<'a> {
   Foo(&'a str),
   Bar(f32)
}

impl<'b> fmt::Display for TestEnum <'b> {
    fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
        println!("Got this far");
        match self{
            &TestEnum::Foo(x) => write!(f,"{}",x),
            &TestEnum::Bar(x) => write!(f,"{}",x),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_print() {
        let cell = TestEnum::Str("foo");
        println!("Printing");
        println!("{}",cell); // No output here
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用{:?}和{}但无济于事.

printing rust

4
推荐指数
1
解决办法
310
查看次数

如何在结构中存储类型为“impl Trait”的变量?

这有效:

let fut = Arc::new(Mutex::new(Box::pin(async { 1 })));

let mut conn_futures = BTreeMap::new(); // implicitly typed
conn_futures.insert(123, fut);
if let Some(fut) = conn_futures.get_mut(&123) {
   let fut = fut.clone();
   self.pool.spawn(async move {
        let mut fut = fut.try_lock().unwrap();
        (&mut *fut).await;
    });
};
Run Code Online (Sandbox Code Playgroud)

我如何在结构中写同样的东西;是什么类型的conn_futures?根据编译器的说法,它是BTreeMap<i32, impl Future>,但无法将其写入结构中:

struct Foo {
    conn_futures: BTreeMap<i32, impl Future>, // impl not allow in this position
}
Run Code Online (Sandbox Code Playgroud)

我试过这个:

use futures::{executor::LocalPool, lock::Mutex, task::SpawnExt, Future}; // 0.3.1
use std::{collections::BTreeMap, pin::Pin, sync::Arc};

struct Foo {
    conn_futures: BTreeMap<i32, Arc<Mutex<Pin<Box<dyn …
Run Code Online (Sandbox Code Playgroud)

future rust

4
推荐指数
1
解决办法
2200
查看次数

传递CString后跟一个int的FFI中的错误

我的Rust测试代码

extern "C" {
fn test_int_only(n : libc::c_int);
fn test_int_and_str(s : CString , n : libc::c_int);
}

pub fn test1() { 
unsafe {
    test_int_only(0);
    test_int_only(1);
    test_int_only(2);
    test_int_only(4);
    test_int_only(-12);
    }
}


pub fn test2() { 
unsafe {
    test_int_and_str(CString::new("Foo").unwrap(),0);
    test_int_and_str(CString::new("Bar").unwrap(),1);
    test_int_and_str(CString::new("Baz").unwrap(),2);
    test_int_and_str(CString::new("Fub").unwrap(),4);
    test_int_and_str(CString::new("Bub").unwrap(),-12);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的C代码

void test_int_only(int abc){
    printf("%d\n", abc);
}

void test_int_and_str(const char* name,int abc) {
    printf("%s %d\n", name, abc);
}
Run Code Online (Sandbox Code Playgroud)

测试test_int_only()时

1
2
4
-12
Run Code Online (Sandbox Code Playgroud)

测试test_int_and_str()时

Foo 4
Bar 4
Baz 4
Fub 4
Bub 4
Run Code Online (Sandbox Code Playgroud)

似乎第二个arg被解释为(在rust或c中)作为sizeof字符串,而不是从Rust代码传递的值.我猜它与调用约定或空终止无法正常工作有关.它是一个C dll,带有_cdecl(windows 32bit …

windows 32-bit ffi rust

3
推荐指数
1
解决办法
66
查看次数

在匹配"结果"并仍然能够捕获错误时使用if-let绑定的惯用方法是什么?

fn lines_from_file<F>(filename: F) -> Result<io::Lines<BufReader<File>>, io::Error>
where
    F: std::convert::AsRef<std::path::Path>,
{
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

fn main() {
    let filename: &str = "input.pdl";
    // This works fine
    match lines_from_file(filename) {
        Ok(lines) => {
            for line in lines {
                println!("{:?}", line);
            },
        }
        Err(e) => println!("Error {:?}", e),
    }
}
Run Code Online (Sandbox Code Playgroud)

我想改用它:

if let lines = Ok(lines_from_file(filename)) {
    for line in lines {
        println!("{:?}", line);
    }
} else {
    println!("Error {:?}" /*what goes here?*/,)
}
Run Code Online (Sandbox Code Playgroud)

但这给出了一个错误:

| if let lines = …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
1961
查看次数

使用可变字符串调用GetUserName WinAPI函数不会填充字符串

这似乎部分工作,但我无法获得要打印的字符串值

pub fn test() {
    let mut buf: Vec<u16> = vec![0; 64];
    let mut sz: DWORD = 0;
    unsafe {
        advapi32::GetUserNameW(buf.as_mut_ptr(), &mut sz);
    }
    let str1 = OsString::from_wide(&buf).into_string().unwrap();
    println!("Here: {} {}", sz, str1);
}
Run Code Online (Sandbox Code Playgroud)

打印:

Here: 10
Run Code Online (Sandbox Code Playgroud)

当我希望它也打印

Here: 10 <username>
Run Code Online (Sandbox Code Playgroud)

作为测试,C版

TCHAR buf[100];
DWORD sz;
GetUserName(buf, &sz);
Run Code Online (Sandbox Code Playgroud)

似乎buf很好.

winapi rust

1
推荐指数
1
解决办法
617
查看次数

如何为循环c ++编写声明14

有没有办法在C++ 14中为循环编写声明式样式

for(int i = 0; i < 10; i+=2) {
    // ... some code
}
Run Code Online (Sandbox Code Playgroud)

我发现最接近的是使用boost

for(auto i : irange(1,10,2)){
     // .... some code
}
Run Code Online (Sandbox Code Playgroud)

是否有c ++ 14/17标准方法可以达到同样的效果?

我试图将std :: make_integer_sequence()作为一个可能的起点,但无法弄明白.

c++ range c++17

0
推荐指数
1
解决办法
406
查看次数

标签 统计

rust ×7

32-bit ×1

c++ ×1

c++17 ×1

dll ×1

enums ×1

ffi ×1

future ×1

lifetime ×1

printing ×1

range ×1

struct ×1

winapi ×1

windows ×1