Sto cercando di creare una libreria dinamica in Rust che esporti una struct come un simbolo che verrà caricato in un programma C tramite dlopen().Creazione di una struct C statica contenente stringhe
Tuttavia, sono in esecuzione in alcuni segfault durante l'accesso alla seconda stringa nella struttura, quindi ho creato un piccolo programma di test per provare a capire cosa sto facendo male.
Questo è il codice Rust (test.rs), compilato con "rustc --crate tipo test.rs dylib":
#[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"
};
Ed ecco il programma C che tenta di caricare la libreria (test.c), compilato con "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) {
printf("failed to dlopen: %s\n", dlerror());
return 1;
}
desc = (plugin_desc *) dlsym(handle, "PLUGIN_DESC");
if (!desc) {
printf("failed to dlsym: %s\n", dlerror());
return 1;
}
printf("name: %p\n", desc->name);
printf("version: %p\n", desc->version);
printf("description: %p\n", desc->description);
return 0;
}
Questa è l'uscita:
name: 0x7fa59ef8d750
version: 0xc
description: 0x7fa59ef8d75c
Come si può vedere, l'annuncio dress of desc-> version è in realtà 0xc (12), che è la lunghezza della prima stringa. Quindi sembra che la struttura che viene impacchettata nella libreria contenga anche la lunghezza della stringa dopo l'indirizzo di memoria.
Sto usando il tipo di stringa errato qui? Come puoi vedere, dovevo anche far terminare manualmente le stringhe NULL. Ho provato ad usare il wrapper CString ma in questo caso non sembra funzionare ("gli oggetti statici non possono avere distruttori").
sto correndo l'ultima nightly Ruggine su Linux:
$ rustc --version
rustc 0.12.0-pre-nightly (f8426e2e2 2014-09-16 02:26:01 +0000)
Hai provato mettendo '* puntatori i8' nella struct invece? – nneonneo
Sembra che le stringhe di ruggine non siano solo 'char *' s. Esiste un file .h che contiene una definizione di stringhe di ruggine per il collegamento con C? – EOF