#bindings #cli #bindings-generator #cli-tool #generate #codebase #dll

bin+lib csbinding_generator

this is a cli tool to generate c# bindings from a rust codebase

1 unstable release

0.5.0 Feb 7, 2022

#200 in FFI

MIT license

10KB
126 lines

C# Binding Generator

this is a cli tool to generate c# bindings from a rust codebase.

Description:

Installation

  1. Get the cli from crates.io: cargo install csbinding
  2. Run the executable: csbinding -h

Help Output

USAGE:
    csbinding.exe [OPTIONS] <SCAN_FOLDER>

ARGS:
    <SCAN_FOLDER>    The folders to start checking from there

OPTIONS:
    -d, --dllname <DLLNAME>        Using this value, you can generate code with the proper dll name
                                   from the start. You can always change it later
    -e, --excluded <EXCLUDED>      Folders/Files excluded from search
    -h, --help                     Print help information
    -n, --namespace <NAMESPACE>    If you want the functions and/or object inside a namespace, add
                                   it with this flag
    -o <OUTPUT_FOLDER>             [default: .]
    -V, --version                  Print version information

Limitations

Under the hood there are some limitations, mostly enforced by my parsing library: csharp_binder. The library will also tries to predict if the bindings generated will be empty and avoid it, no guaranties for now. Maybe later with custom c# generation

I assume that all *.rs files in the folder provided will be part of the same dll and as such, only 1 dll name argument is given. If your project crates multiples dll files your will have to edit the bindings with the proper names.

Three types can be exported: Enums, Structs and Functions. Not all of them though. An Enum should be annotated with #[repr(u8)] or any other bigger Integer. A Struct must be annotated with #[repr(C)] to have the correct memory representation. A function should also have a pub extern "C" annotation to be exported properly.

For every rust file that contains exports a new c# file will be generated. It will be better for you to give an output folder for the bindings

Warning

Don't export any Rust specific types like static arrays, Vec, String, or slices. Also nothing from std. If you want to export/import lists then do it with pointers and a size arguments.

Examples

In the examples folder the are 2 project. One in rust, that generates a library, and one in c# that uses the library to work. Below you can find some examples instruction run will help you run the project. Keep in mind that the are run in windows cmd, adjust them to your terminal environment.

# Create the bindings
csbindinglib -o examples\test_env -d print_string.dll examples\print_string

# Generate library
cd examples\print_string
cargo b --release

# Copy dll to c# project
cd ..\..
copy examples\print_string\target\release\print_string.dll examples\test_env

# Run test environment
cd examples\test_env
dotnet run

Dependencies

~3MB
~62K SLoC