Automatically generates C# `DllImport` code from Rust `extern "C" fn` code. Whereas DllImport defaults to the Windows calling convention and requires a lot of configuration for C calls, csbindgen generates code optimized for "Cdecl" calls. Also .NET and Unity have different callback invocation methods (.NET uses function pointers, while Unity uses MonoPInvokeCallback), but you can output code for either by configuration.
When used with Rust's excellent C integration, you can also bring C libraries into C#.
There are usually many pains involved in using the C Library with C#. Not only is it difficult to create bindings, but cross-platform builds are very difficult. In this day and age, you have to build for multiple platforms and architectures, windows, osx, linux, android, ios, each with x64, x86, arm.
[Rust](https://www.rust-lang.org/) has an excellent toolchain for cross-platform builds, as well as [cc crate](https://crates.io/crates/cc), [cmake crate](https://crates.io/crates/cmake) allow C source code to be integrated into the build. And [rust-bindgen](https://crates.io/crates/bindgen), which generates bindings from `.h`, is highly functional and very stable.
csbindgen can easily bring native C libraries into C# through Rust. csbindgen generates Rust extern code and C# DllImport code to work with C# from code generated from C by bindgen. With cc crate or cmake crate, C code is linked to the single rust native library.
Getting Started
---
Install on `Cargo.toml` as `build-dependencies` and set up `bindgen::Builder` on `build.rs`.
`csharp_dll_name_if` is optional. If specified, `#if` allows two DllName to be specified, which is useful if the name must be `__Internal` at iOS build.
### Unity Callback
`csharp_use_function_pointer` configures how generate function pointer. The default is to generate a `delegate*`, but Unity does not support it; setting it to `false` will generate a `Func/Action` that can be used with `MonoPInvokeCallback`.
`method_filter` allows you to specify which methods to exclude; if unspecified, methods prefixed with `_` are excluded by default. C libraries are usually published with a specific prefix. For example, [LZ4](https://github.com/lz4/lz4) is `LZ4`, [ZStandard](https://github.com/facebook/zstd) is `ZSTD_`, [quiche](https://github.com/cloudflare/quiche) is `quiche_`, [Bullet Physics SDK](https://github.com/bulletphysics/bullet3) is `b3`.
| `extern "C" fn` | `delegate* unmanaged[Cdecl]<>` or `Func<>/Action<>` |
| `Option<extern "C" fn>` | `delegate* unmanaged[Cdecl]<>` or `Func<>/Action<>` |
| `*mut T` | `T*` |
| `*const T` | `T*` |
| `*mut *mut T` | `T**` |
| `*const *const T` | `T**` |
csbindgen is designed to return primitives that do not cause marshalling. It is better to convert from pointers to Span yourself than to do the conversion implicitly and in a black box. This is a recent trend, such as the addition of [DisableRuntimeMarshalling](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.disableruntimemarshallingattribute) from .NET 7.
`c_long` and `c_ulong` will convert to [CLong](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.clong), [CULong](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.culong) struct after .NET 6. If you want to convert in Unity, you will need Shim.
```csharp
// Currently Unity is .NET Standard 2.1 so does not exist CLong and CULong
namespace System.Runtime.InteropServices
{
internal struct CLong
{
public int Value; // #if Windows = int, Unix x32 = int, Unix x64 = long
}
internal struct CULong
{
public uint Value; // #if Windows = uint, Unix x32 = uint, Unix x64 = ulong
}
}
```
### Struct
csbindgen supports `Struct`, you can define `#[repr(C)]` struct on method parameter or return value.
You can also pass memory allocated by C# to Rust (use `fixed` or `GCHandle.Alloc(Pinned)`). The important thing is that memory allocated in Rust must release in Rust and memory allocated in C# must release in C#.
If you want to pass a non FFI Safe struct, cast it to `*mut c_void`. Then C# will treat it as a `void*`. csbindgen does not support Opaque Type.
Rust's String, Array(Vec) and C#'s String, Array is different thing. Since it cannot be shared, pass it with a pointer and handle it with slice(Span) or materialize it if necessary.
`CString` is null-terminated string. It can send by `*mut c_char` and received as `byte*` in C#.
// null-terminated `byte*` or sbyte* can materialize by new String()
var cString = NativeMethods.alloc_c_string();
var str = new String((sbyte*)cString);
NativeMethods.free_c_string(cString);
```
Rust's String is UTF-8(`Vec<u8>`) but C# String is UTF-16. Andalso, `Vec<>` can not send to C# so require to convert pointer and control memory manually. Here is the buffer manager for FFI.
```rust
#[repr(C)]
pub struct ByteBuffer {
ptr: *mut u8,
length: i32,
capacity: i32,
}
impl ByteBuffer {
pub fn len(&self) -> usize {
self.length
.try_into()
.expect("buffer length negative or overflowed")
}
pub fn from_vec(bytes: Vec<u8>) -> Self {
let length = i32::try_from(bytes.len()).expect("buffer length cannot fit into a i32.");
let capacity =
i32::try_from(bytes.capacity()).expect("buffer capacity cannot fit into a i32.");
// drop inner buffer, if you need Vec<i32>, use buf.destroy_into_vec_struct::<i32>() instead.
buf.destroy();
}
```
```csharp
var u8String = NativeMethods.alloc_u8_string();
var u8Buffer = NativeMethods.alloc_u8_buffer();
var i32Buffer = NativeMethods.alloc_i32_buffer();
try
{
var str = Encoding.UTF8.GetString(u8String->AsSpan());
Console.WriteLine(str);
Console.WriteLine("----");
var buffer = u8Buffer->AsSpan();
foreach (var item in buffer)
{
Console.WriteLine(item);
}
Console.WriteLine("----");
var i32Span = i32Buffer->AsSpan<int>();
foreach (var item in i32Span)
{
Console.WriteLine(item);
}
}
finally
{
NativeMethods.free_u8_string(u8String);
NativeMethods.free_u8_buffer(u8Buffer);
NativeMethods.free_i32_buffer(i32Buffer);
}
```
C# to Rust would be a bit simpler to send, just pass byte* and length. In Rust, use `std::slice::from_raw_parts` to create slice. Again, the important thing is that memory allocated in Rust must release in Rust and memory allocated in C# must release in C#.
Build Tracing
---
csbindgen silently skips over any method with a non-generatable type. If you build with `cargo build -vv`, you will get thse message if not geneated.
*`csbindgen can't handle this parameter type so ignore generate, method_name: {} parameter_name: {}`
*`csbindgen can't handle this return type so ignore generate, method_name: {}`