在下面的代码中创建字符串缓冲区 是我发现的最快的方式,因为没有完成分配解除分配 如果我理解正确
pub extern fn rust_print_file() -> *mut PackChar {
//set min size to 50 - avoid expanding when line count is 50 or less
let mut out_vec = Vec::with_capacity(50);
let mut curdr = env::current_dir().unwrap();//get path to file dir
let fl_str = "file_test.txt";
curdr.push(fl_str);//created full path to be used
let file = BufReader::new(File::open(curdr).unwrap());
//here i try to accommodate each line in a struct
let mut line_index = 0;
for line in file.lines() {
let cur_line = line.unwrap();
let loclbuf_size = cur_line.len();
let mut loclbuf = String::with_capacity(buffer_size);
//i tried two ways
loclbuf.push_str(cur_line.unwrap()); // can't be done
loclbuf.push_str(line.unwrap()); // can't be done too
let pack_char = PackChar {
int_val: line_index,
buffer_size: loclbuf_size as i32,
buffer: loclbuf.as_ptr() as *mut _,
};
line_index+=1;
mem::forget(buffer);
out_vec.push(pack_char);
}
Box::into_raw(out_vec.into_boxed_slice()) as *mut _
}
这是我用来传递给C#
的结构#[repr(C)]
pub struct PackChar {
pub int_val: c_int,
pub buffer: *mut c_char,
pub buffer_size: c_int,
}
生成一些虚拟文本时 我已经检查过了,它正确地将数据传递到"另一方"使用它。 但不是读取行任务,生成的文本如上所示。
这是我尝试的另一种方式,虽然我更喜欢上面的代码,但是这会引发编译错误。
错误:在buffer
上使用移动的值:forget(buffer)
[E0382]
#[no_mangle]
pub extern fn rust_return_file_read_lines() -> *mut PackChar {
let mut out_vec = Vec::with_capacity(50);
let mut curdr = env::current_dir().unwrap();
let fl_str = "file_test.txt";
curdr.push(fl_str);
let file = BufReader::new(File::open(curdr).unwrap());
let mut lindex = 0;
for line in file.lines() {
let tmpbuffer = line.unwrap().into_bytes();
let tmpbuffer_size = buffer.len();
let pack_char = PackChar {
int_val: lindex,
buffer_size: tmpbuffer_size as i32,
buffer: Box::into_raw(tmpbuffer.into_boxed_slice()) as *mut _
};
lindex+=1;
mem::forget(buffer);
out_vec.push(pack_char);
}
Box::into_raw(out_vec.into_boxed_slice()) as *mut _
}
修改 只要缓冲区的类型:
buffer: loclbuf.as_ptr() as *mut _,
我可以正确地将数据传递给c#。 所以我怎么能以这种方式读取行,所以每个都会按照描述存储到缓冲区中?
答案 0 :(得分:3)
因为现在看来我的视觉工作室似乎有一个错误,它不是第一次发生但是因为我是新生锈我确信代码是错误的。
这对我有用,我很乐意收到意见和建议
extern crate libc;
use std::env;
use libc::c_char;
use libc::c_int;
use std::mem;
use std::io::{BufReader, BufRead};
use std::fs::File;
#[repr(C)]
pub struct PackChar {
pub int_val: c_int,
pub buffer: *mut c_char, // changed
pub dbuffer_size: c_int, // added
}
#[no_mangle]
pub extern fn rust_print_file() -> *mut PackChar {
let mut out_vec = Vec::with_capacity(50 as usize);
let mut cwd = env::current_dir().unwrap();
let fl_str = "file_test.txt";
cwd.push(fl_str);
let file = BufReader::new(File::open(cwd).unwrap());
for (index, line) in file.lines().enumerate() {
let buffer = line.unwrap();
let buffer_size = buffer.len();
let pack_char = PackChar {
int_val: index as i32,
dbuffer_size: buffer_size as i32,
buffer: buffer.as_ptr() as *mut _,
};
mem::forget(buffer); // don't deallocate memory
out_vec.push(pack_char);
}
Box::into_raw(out_vec.into_boxed_slice()) as *mut _ // changed
}