我正在尝试找到一种方便的方法来初始化'pod'C++结构.现在,考虑以下结构:
struct FooBar {
int foo;
float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
Run Code Online (Sandbox Code Playgroud)
如果我想在C(!)中方便地初始化它,我可以简单地写:
/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
Run Code Online (Sandbox Code Playgroud)
请注意,我想明确地避免使用以下表示法,因为如果我将来更改结构中的任何内容,它会让我感到沮丧:
/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
Run Code Online (Sandbox Code Playgroud)
为了实现与/* A */示例中相同(或至少类似)的C++ ,我将不得不实现一个愚蠢的构造函数:
FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// -> …Run Code Online (Sandbox Code Playgroud) 我正在尝试获取C库返回的C字符串,并通过FFI将其转换为Rust字符串.
mylib.c
const char* hello(){
return "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)
main.rs
#![feature(link_args)]
extern crate libc;
use libc::c_char;
#[link_args = "-L . -I . -lmylib"]
extern {
fn hello() -> *c_char;
}
fn main() {
//how do I get a str representation of hello() here?
}
Run Code Online (Sandbox Code Playgroud) 这是一个后续问题的答案,以是否有可能的typedef指针到extern-"C" -函数模板中的类型?
此代码无法使用g++Visual C/C++和Comeau C/C++进行编译,并且具有基本相同的错误消息:
#include <cstdlib>
extern "C" {
static int do_stuff(int) {
return 3;
}
template <typename return_t_, typename arg1_t_>
struct test {
static void foo(return_t_ (*)(arg1_t_)) { }
};
}
int main()
{
test<int, int>::foo(&do_stuff);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
g ++说"错误:带C链接的模板",Visual C/C++发出编译器错误C2894,而Comeau C/C++说"错误:此声明可能没有extern"C"链接".
问题是,所有人都满意:
#include <cstdlib>
extern "C" {
static int do_stuff(int) {
return 3;
}
struct test {
static void foo(int (*)(int)) { }
};
}
int main()
{
test::foo(&do_stuff); …Run Code Online (Sandbox Code Playgroud) 有没有简单的方法来复制C字符串?
我有const char *stringA,我想char *stringB取值(注意stringB不是const).我试过stringB=(char*) stringA,但这stringB仍然指向相同的内存位置,所以当stringA以后的更改时,stringB也是如此.
我也试过strcpy(stringB,stringA),但似乎如果stringB没有初始化为足够大的数组,那就是段错误.我对C字符串没有超级经验,我错过了一些明显的东西吗?如果我只是初始化stringB为char *stringB[23],因为我知道我永远不会有一个比22字符更长的字符串(并允许空终止符),这是正确的方法吗?如果stringB检查是否与其他C字符串相等,那么额外的空格是否会影响任何内容?
(并且在这里使用字符串不是解决方案,因为我需要最小的开销并且可以轻松访问单个字符)