如何在Rust FFI中发布常量字符串? [英] How to publish a constant string in the Rust FFI?

查看:197
本文介绍了如何在Rust FFI中发布常量字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让Rust库向C公开const char *静态字符串,以与现有接口兼容(特别是 librsync ).也就是说,C头文件具有

I want to have a Rust library expose a const char * static string to C, to be compatible with an existing interface (specifically librsync). That is, the C header file has

extern char const *my_string;

在C语言中,库将简单地具有

In C, the library would simply have

char const *my_string = "hi";

在Rust中,我尝试过类似的操作

In Rust I've tried something like

pub static my_string: *const libc::c_char = unsafe { "hi\0" as *const libc::c_char };

但这可抱怨

error: casting `&'static str` as `*const i8` is invalid

似乎我不能使用CString等,因为它们不会是编译时常量表达式.

It seems like I can't use CString etc because they won't be a compile-time constant expression.

推荐答案

我们需要一个公共的,静态的,未修饰的指向某些零终止字节的指针:

We need a public, static, unmangled pointer to some zero-terminated bytes:

#[export_name = "CONST_C_STR"] // or #[no_mangle]
pub static CONST_C_STR: &[u8; 20] = b"a constant c string\0";

这与一个简单的C程序一起工作:

This worked with a simple C program:

#include <stdio.h>

extern char * CONST_C_STR;

int main(int argc, char *argv[]) {
  printf("%s\n", CONST_C_STR);
}

这篇关于如何在Rust FFI中发布常量字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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