相关疑难解决方法(0)

创建包含字符串的静态C结构

我正在尝试在Rust中创建一个动态库,它导出一个结构作为符号,将通过dlopen()加载到C程序中.

但是,当我访问结构中的第二个字符串时,我遇到了一些段错误,所以我做了一个小测试程序,试着弄清楚我做错了什么.

这是Rust代码(test.rs),使用"rustc --crate-type dylib test.rs"编译:

#[repr(C)]
pub struct PluginDesc {
    name: &'static str,
    version: &'static str,
    description: &'static str
}


#[no_mangle]
pub static PLUGIN_DESC: PluginDesc = PluginDesc {
    name: "Test Plugin\0",
    version: "1.0\0",
    description: "Test Rust Plugin\0"
};
Run Code Online (Sandbox Code Playgroud)

这是尝试加载库(test.c)的C程序,使用"gcc test.c -ldl -o test"编译:

#include <dlfcn.h>
#include <stdio.h>


typedef struct {
    const char *name;
    const char *version;
    const char *description;
} plugin_desc;


int main(int argc, char **argv) {
    void *handle;
    plugin_desc *desc;

    handle = dlopen("./libtest.so", RTLD_LOCAL | RTLD_LAZY);
    if (!handle) …
Run Code Online (Sandbox Code Playgroud)

c string struct dlopen rust

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

标签 统计

c ×1

dlopen ×1

rust ×1

string ×1

struct ×1