PistonDevelopers / VisualRust

Visual Studio extension for Rust
MIT License
701 stars 73 forks source link

How to create dll with ext.crates/dependencies? #270

Closed stukii closed 7 years ago

stukii commented 7 years ago

I am creating a .dll that I am calling from c# with this in my cargo.toml

[lib]
name = "myLib"
crate-type = ["dylib"] 

my lib.rs contains

#![crate_type = "lib"]
#[no_mangle]

And I am perfectly able to call the function pub extern "C" fn myFunc.. from C#.

Until I add a extern crate like extern crate rand; Then it does no longer find the entry point on C#.

When only adding

[dependencies]
rand = "0.3"

to the cargo it does change the outcoming dll but it really only becomes unusable when adding the crate in the script.

What can I do to use external crates from my pinvoked rust-dlls?

retep998 commented 7 years ago

Why do you specify the crate type both in your Cargo.toml and lib.rs, and why are they different? Also, both dylib and lib are the wrong crate type to have a .dll that can be used from C#. What you really want is the cdylib crate type.

Remember that the #[no_mangle] has to be attached directly to each function that you're exporting to be used from C#.

stukii commented 7 years ago

Thank you! I was using the no_mangle incorrectly. For anyone Interested how to make libs in rust and call from c#:

lib.rs

extern crate rand;
#[no_mangle]
pub extern "C" fn rsRandomI32() -> u32 {
    println!("entry rust");
    let rnum = rand::random::<u32>();
    println!("rnd : {}",rnum);
    rnum
}

cargo.toml

[dependencies]
rand = { git = "https://github.com/rust-lang-nursery/rand" }

[lib]
name = "myLibName"
crate-type = ["cdylib"] 

compile and use the .dll in c#

class Program
    {
        [DllImport(@"Path\myLibName.dll")]
        private static extern int rsRandomI32();
        static void Main(string[] args)
        {
            Console.WriteLine($"result in c#:{rsRandomI32()}");
        }
    }
retep998 commented 7 years ago

Why does your Cargo.toml still have a crate type of dylib instead of cdylib?

stukii commented 7 years ago

Changed it, ty :)