0

I'm compiling some information of an object into an .so, like:

#[no_mangle]
pub static a: [f32; 10] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];

(simplified of course)

I need to have access to its values from another .so and thinking on simplifying the process, instead of creating a function that returns a Vec<f32> for example, I want to return a fixed size array since this will not change, like:

use libloading::{Library, Symbol};
...

unsafe {

        let lib = Library::new("path/to/lib.so").unwrap();

        let a: Symbol< * mut [f32; 10] > = lib.get(b"a\0").unwrap();

        println!("{:?}", **a); // To check what is being retrieved

    }
...

So far the output being printed is:

[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

Which is correct, but I cannot access it's elements, like:

let b = a[0];

When compiling:

error[E0608]: cannot index into a value of type `libloading::Symbol<'_, *mut [f32; 10]>`

How to have access to the values or even assign the whole array to a new one in the caller .so?

mbfernan
  • 13
  • 5
  • You probably need to dereference the symbol manually. Something like: `let b = a.deref()[0];` – Jmb Apr 27 '21 at 07:10

1 Answers1

0

If you want to access the elements, you will have to dereference the Symbol and the mutable pointer first, like you already correctly did when printing the full array.

So if you want to access only the first element you will have to use (**a)[0] or (**a)[7] if you want to retrieve the eigth element.

Here is the full example based on the code in your question:

use libloading::{Library, Symbol};

fn main() {
    unsafe {
        let lib = Library::new("libarray_lib.dylib").unwrap();

        let a: Symbol< * mut [f32; 10] > = lib.get(b"a\0").unwrap();
        println!("{:?}", **a); // To check what is being retrieved
        println!("{}", (**a)[0]); // Dereference a and access its first element

    }
}
frankenapps
  • 5,800
  • 6
  • 28
  • 69