- Notifications
You must be signed in to change notification settings - Fork67
Generate C# FFI from Rust for automatically brings native code and C native library to .NET and Unity.
License
Cysharp/csbindgen
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Generate C# FFI from Rust for automatically brings native code and C native library to .NET and Unity.
Automatically generates C#DllImport
code from Rustextern "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 has an excellent toolchain for cross-platform builds, as well ascc crate,cmake crate allow C source code to be integrated into the build. Andrust-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.
showcase:
- lz4_bindgen.cs :LZ4 compression library C# binding
- zstd_bindgen.cs :Zstandard compression library C# binding
- quiche_bindgen.cs :cloudflare/quiche QUIC and HTTP/3 library C# binding
- bullet3_bindgen.cs :Bullet Physics SDK C# binding
- sqlite3_bindgen.cs :SQLite C# binding
- Cysharp/YetAnotherHttpHandler : brings the power of HTTP/2 (and gRPC) to Unity and .NET Standard
- Cysharp/MagicPhysX : .NET PhysX 5 binding to all platforms(win, osx, linux)
Install onCargo.toml
asbuild-dependencies
and set upbindgen::Builder
onbuild.rs
.
[package]name ="example"version ="0.1.0"[lib]crate-type = ["cdylib"][build-dependencies]csbindgen ="1.8.0"
You can bring Rust FFI code to C#.
// lib.rs, simple FFI code#[no_mangle]pubextern"C"fnmy_add(x:i32,y:i32) ->i32{ x + y}
Setup csbindgen code tobuild.rs
.
fnmain(){ csbindgen::Builder::default().input_extern_file("lib.rs").csharp_dll_name("example").generate_csharp_file("../dotnet/NativeMethods.g.cs").unwrap();}
csharp_dll_name
is for specifying[DllImport({DLL_NAME}, ...)]
on the C# side, which should match the name of the dll binary.See#library-loading section for how to resolve the dll file path.
Note
In this example, the value ofcsharp_dll_name
is output by the Rust project you set up.In the above,package.name
in the Cargo.toml is set to "example". By default, the following binaries should be output to thetarget/
folder of the Rust project.
- Windows: example.dll
- Linux: libexample.so
- macOS: libexample.dylib
The filename without the extension should be specified to DllImport. Be careful that by default, rust compiler prefixes filenames with "lib" in some environments.So if you want to try this example as is on macOS,csharp_dll_name
would be "libexample".
Then, let's runcargo build
it will generate this C# code.
// NativeMethods.g.csusingSystem;usingSystem.Runtime.InteropServices;namespaceCsBindgen{internalstaticunsafepartialclassNativeMethods{conststring__DllName="example";[DllImport(__DllName,EntryPoint="my_add",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexternintmy_add(intx,inty);}}
For example, buildlz4 compression library.
// using bindgen, generate binding codebindgen::Builder::default().header("c/lz4/lz4.h").generate().unwrap().write_to_file("lz4.rs").unwrap();// using cc, build and link c codecc::Build::new().file("lz4.c").compile("lz4");// csbindgen code, generate both rust ffi and C# dll importcsbindgen::Builder::default().input_bindgen_file("lz4.rs")// read from bindgen generated code.rust_file_header("use super::lz4::*;")// import bindgen generated modules(struct/method).csharp_entry_point_prefix("csbindgen_")// adjust same signature of rust method and C# EntryPoint.csharp_dll_name("liblz4").generate_to_file("lz4_ffi.rs","../dotnet/NativeMethods.lz4.g.cs").unwrap();
It will generates like these code.
// lz4_ffi.rs#[allow(unused)]use::std::os::raw::*;usesuper::lz4::*;#[no_mangle]pubunsafeextern"C"fncsbindgen_LZ4_compress_default(src:*constc_char,dst:*mutc_char,srcSize:c_int,dstCapacity:c_int) ->c_int{LZ4_compress_default(src, dst, srcSize, dstCapacity)}
// NativeMethods.lz4.g.csusingSystem;usingSystem.Runtime.InteropServices;namespaceCsBindgen{internalstaticunsafepartialclassNativeMethods{conststring__DllName="liblz4";[DllImport(__DllName,EntryPoint="csbindgen_LZ4_compress_default",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexternintLZ4_compress_default(byte*src,byte*dst,intsrcSize,intdstCapacity);}}
Finally import generated module onlib.rs
.
// lib.rs, import generated codes.#[allow(dead_code)]#[allow(non_snake_case)]#[allow(non_camel_case_types)]#[allow(non_upper_case_globals)]mod lz4;#[allow(dead_code)]#[allow(non_snake_case)]#[allow(non_camel_case_types)]mod lz4_ffi;
Rust to C#, use theinput_extern_file
-> setup options ->generate_csharp_file
.
csbindgen::Builder::default().input_extern_file("src/lib.rs")// required.csharp_dll_name("mynativelib")// required.csharp_class_name("NativeMethods")// optional, default: NativeMethods.csharp_namespace("CsBindgen")// optional, default: CsBindgen.csharp_class_accessibility("internal")// optional, default: internal.csharp_entry_point_prefix("")// optional, default: "".csharp_method_prefix("")// optional, default: "".csharp_use_function_pointer(true)// optional, default: true.csharp_disable_emit_dll_name(false)// optional, default: false.csharp_imported_namespaces("MyLib")// optional, default: empty.csharp_generate_const_filter(|_|false)// optional, default: `|_|false`.csharp_dll_name_if("UNITY_IOS && !UNITY_EDITOR","__Internal")// optional, default: "".csharp_type_rename(|rust_type_name|match rust_type_name{// optional, default: `|x| x`"FfiConfiguration" =>"Configuration".into(), _ => x,}).generate_csharp_file("../dotnet-sandbox/NativeMethods.cs")// required.unwrap();
csharp_*
configuration will be embedded in the placeholder of the output file.
usingSystem;usingSystem.Runtime.InteropServices;using{csharp_imported_namespaces};namespace{csharp_namespace}{{csharp_class_accessibility}staticunsafepartialclass{csharp_class_name}{#if{csharp_dll_name_if(if_symbol,...)}conststring__DllName="{csharp_dll_name_if(...,if_dll_name)}";#elseconststring__DllName="{csharp_dll_name}";#endif}{csharp_generate_const_filter}[DllImport(__DllName,EntryPoint="{csharp_entry_point_prefix}LZ4_versionNumber",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)] publicstaticexternint{csharp_method_prefix}LZ4_versionNumber();}
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.
csharp_disable_emit_dll_name
is optional, if set to true then don't emitconst string __DllName
. It is useful for generate same class-name from different builder.
csharp_generate_const_filter
is optional, if set a filter fun, then generate filter C#const
field from Rustconst
.
input_extern_file
andinput_bindgen_file
allow mulitple call, if you need to add dependent struct, use this.
csbindgen::Builder::default().input_extern_file("src/lib.rs").input_extern_file("src/struct_modules.rs").generate_csharp_file("../dotnet-sandbox/NativeMethods.cs");
alsocsharp_imported_namespaces
can call multiple times.
csharp_use_function_pointer
configures how generate function pointer. The default is to generate adelegate*
, but Unity does not support it; setting it tofalse
will generate aFunc/Action
that can be used withMonoPInvokeCallback
.
// true(default) generates delegate*[DllImport(__DllName,EntryPoint="callback_test",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexternintcallback_test(delegate* unmanaged[Cdecl]<int,int>cb);// You can define like this callback method.[UnmanagedCallersOnly(CallConvs=new[]{typeof(CallConvCdecl)})]staticintMethod(intx)=>x*x;// And use it.callback_test(&Method);// ---// false will generates {method_name}_{parameter_name}_delegate, it is useful for Unity[UnmanagedFunctionPointer(CallingConvention.Cdecl)]publicdelegateintcallback_test_cb_delegate(inta);[DllImport(__DllName,EntryPoint="callback_test",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexternintcallback_test(callback_test_cb_delegatecb);// Unity can define callback method as MonoPInvokeCallback[MonoPInvokeCallback(typeof(NativeMethods.callback_test_cb_delegate))]staticintMethod(intx)=>x*x;// And use it.callback_test(Method);
input_bindgen_file
-> setup options ->generate_to_file
to use C to C# workflow.
csbindgen::Builder::default().input_bindgen_file("src/lz4.rs")// required.method_filter(|x|{ x.starts_with("LZ4")})// optional, default: |x| !x.starts_with('_').rust_method_prefix("csbindgen_")// optional, default: "csbindgen_".rust_file_header("use super::lz4::*;")// optional, default: "".rust_method_type_path("lz4")// optional, default: "".csharp_dll_name("lz4")// required.csharp_class_name("NativeMethods")// optional, default: NativeMethods.csharp_namespace("CsBindgen")// optional, default: CsBindgen.csharp_class_accessibility("internal")// optional, default: internal.csharp_entry_point_prefix("csbindgen_")// required, you must set same as rust_method_prefix.csharp_method_prefix("")// optional, default: "".csharp_use_function_pointer(true)// optional, default: true.csharp_imported_namespaces("MyLib")// optional, default: empty.csharp_generate_const_filter(|_|false)// optional, default:|_|false.csharp_dll_name_if("UNITY_IOS && !UNITY_EDITOR","__Internal")// optional, default: "".csharp_type_rename(|rust_type_name|match rust_type_name.as_str(){// optional, default: `|x| x`"FfiConfiguration" =>"Configuration".into(), _ => x,}).csharp_file_header("#if !UNITY_WEBGL")// optional, default: "".csharp_file_footer("#endif")// optional, default: "".generate_to_file("src/lz4_ffi.rs","../dotnet-sandbox/lz4_bindgen.cs")// required.unwrap();
It will be embedded in the placeholder of the output file.
#[allow(unused)]use::std::os::raw::*;{rust_file_header}#[no_mangle]pubunsafeextern"C"fn{rust_method_prefix}LZ4_versionNumber() -> c_int{{rust_method_type_path}::LZ4_versionNumber()}
csharp_*
option template is same as Rust to C#, see above documentation.
Adjustrust_file_header
for match your module configuration, recommend to use::*
, also usingrust_method_type_path
that add explicitly resolve path.
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 isLZ4
,ZStandard isZSTD_
,quiche isquiche_
,Bullet Physics SDK isb3
.
rust_method_prefix
andcsharp_method_prefix
orcsharp_entry_point_prefix
must be adjusted to match the method name to be called.
If the file path to be loaded needs to be changed depending on the operating system, the following load code can be used.
internalstaticunsafepartialclassNativeMethods{// https://docs.microsoft.com/en-us/dotnet/standard/native-interop/cross-platform// Library path will search// win => __DllName, __DllName.dll// linux, osx => __DllName.so, __DllName.dylibstaticNativeMethods(){NativeLibrary.SetDllImportResolver(typeof(NativeMethods).Assembly,DllImportResolver);}staticIntPtrDllImportResolver(stringlibraryName,Assemblyassembly,DllImportSearchPath?searchPath){if(libraryName==__DllName){varpath="runtimes/";varextension="";if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){path+="win-";extension=".dll";}elseif(RuntimeInformation.IsOSPlatform(OSPlatform.OSX)){path+="osx-";extension=".dylib";}else{path+="linux-";extension=".so";}if(RuntimeInformation.ProcessArchitecture==Architecture.X86){path+="x86";}elseif(RuntimeInformation.ProcessArchitecture==Architecture.X64){path+="x64";}elseif(RuntimeInformation.ProcessArchitecture==Architecture.Arm64){path+="arm64";}path+="/native/"+__DllName+extension;returnNativeLibrary.Load(Path.Combine(AppContext.BaseDirectory,path),assembly,searchPath);}returnIntPtr.Zero;}}
If Unity, configure Platform settings in each native library's inspector.
In an object-oriented style, it is common to create methods that take a pointer to a state (this) as their first argument. With csbindgen, you can group these methods using extension methods by specifying a Source Generator on the C# side.
Install csbindgen from NuGet, and specify [GroupedNativeMethods] for the partial class of the generated extension methods.
PM> Install-Packagecsbindgen
// create new file and write same type-name with same namespacenamespaceCsBindgen{// append `GroupedNativeMethods` attribute[GroupedNativeMethods]internalstaticunsafepartialclassNativeMethods{}}
// original methods[DllImport(__DllName,EntryPoint="counter_context_insert",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexternvoidcounter_context_insert(counter_context*context,intvalue);// generated methodspublicstaticvoidInsert(thisrefglobal::CsBindgen.counter_context@context,int@value)// ----counter_context*context=NativeMethods.create_counter_context();// standard styleNativeMethods.counter_context_insert(context,10);// generated stylecontext->Insert(10);
GroupedNativeMethods
has four configuration parameters.
publicGroupedNativeMethodsAttribute(string removePrefix= "",string removeSuffix= "",bool removeUntilTypeName= true,bool fixMethodName= true)
The convention for function names when using this feature is as follows:
- The first argument must be a pointer type.
removeUntilTypeName
will remove until find type-name in method-name.- For example
foo_counter_context_insert(countext_context* foo)
->Insert
. - As a result, it is recommended to use a naming convention where the same type name is placed immediately before the verb.
- For example
Rust types will map these C# types.
Rust | C# |
---|---|
i8 | sbyte |
i16 | short |
i32 | int |
i64 | long |
i128 | Int128 |
isize | nint |
u8 | byte |
u16 | ushort |
u32 | uint |
u64 | ulong |
u128 | UInt128 |
usize | nuint |
f32 | float |
f64 | double |
bool | [MarshalAs(UnmanagedType.U1)]bool |
char | uint |
() | void |
c_char | byte |
c_schar | sbyte |
c_uchar | byte |
c_short | short |
c_ushort | ushort |
c_int | int |
c_uint | uint |
c_long | CLong |
c_ulong | CULong |
c_longlong | long |
c_ulonglong | ulong |
c_float | float |
c_double | double |
c_void | void |
CString | sbyte |
NonZeroI8 | sbyte |
NonZeroI16 | short |
NonZeroI32 | int |
NonZeroI64 | long |
NonZeroI128 | Int128 |
NonZeroIsize | nint |
NonZeroU8 | byte |
NonZeroU16 | ushort |
NonZeroU32 | uint |
NonZeroU64 | ulong |
NonZeroU128 | UInt128 |
NonZeroUsize | nuint |
#[repr(C)]Struct | [StructLayout(LayoutKind.Sequential)]Struct |
#[repr(C)]Union | [StructLayout(LayoutKind.Explicit)]Struct |
#[repr(u*/i*)]Enum | Enum |
bitflags! | [Flags]Enum |
extern "C" fn | delegate* unmanaged[Cdecl]<> orFunc<>/Action<> |
Option<extern "C" fn> | delegate* unmanaged[Cdecl]<> orFunc<>/Action<> |
*mut T | T* |
*const T | T* |
*mut *mut T | T** |
*const *const T | T** |
*mut *const T | T** |
*const *mut T | T** |
&T | T* |
&mut T | T* |
&&T | T** |
&*mut T | T** |
NonNull<T> | T* |
Box<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 ofDisableRuntimeMarshalling from .NET 7.
Older C# version do not supportnint
andnuint
. You can usecsharp_use_nint_types
to useIntPtr
andUIntPtr
in their place:
csbindgen::Builder::default().input_extern_file("lib.rs").csharp_dll_name("nativelib").generate_csharp_file("../dotnet/NativeMethods.g.cs").csharp_use_nint_types(false).unwrap();
c_long
andc_ulong
will convert toCLong,CULong struct after .NET 6. If you want to convert in Unity, you will need Shim.
// Currently Unity is .NET Standard 2.1 so does not exist CLong and CULongnamespaceSystem.Runtime.InteropServices{internalstructCLong{publicintValue;// #if Windows = int, Unix x32 = int, Unix x64 = long}internalstructCULong{publicuintValue;// #if Windows = uint, Unix x32 = uint, Unix x64 = ulong}}
csbindgen supportsStruct
, you can define#[repr(C)]
struct on method parameter or return value.
// If you define this struct...#[repr(C)]pubstructMyVector3{pubx:f32,puby:f32,pubz:f32,}#[no_mangle]pubextern"C"fnpass_vector3(v3:MyVector3){println!("{}, {}, {}", v3.x, v3.y, v3.z);}
// csbindgen generates this C# struct[StructLayout(LayoutKind.Sequential)]internalunsafepartialstructMyVector3{publicfloatx;publicfloaty;publicfloatz;}
Also supports tuple struct, it will generateItem*
fields in C#.
#[repr(C)]pub struct MyIntVec3(i32, i32, i32);
[StructLayout(LayoutKind.Sequential)]internalunsafepartialstructMyIntVec3{publicintItem1;publicintItem2;publicintItem3;}
It also supports unit struct, but there is no C# struct that is synonymous with Rust's unit struct (0 byte), so it cannot be materialized. Instead of using void*, it is recommended to use typed pointers.
// 0-byte in Rust#[repr(C)]pub struct MyContext;
// 1-byte in C#[StructLayout(LayoutKind.Sequential)]internalunsafepartialstructMyContext{}
Union
will generate[FieldOffset(0)]
struct.
#[repr(C)]pubunionMyUnion{pubfoo:i32,pubbar:i64,}#[no_mangle]pubextern"C"fnreturn_union() ->MyUnion{MyUnion{bar:53}}
[StructLayout(LayoutKind.Explicit)]internalunsafepartialstructMyUnion{[FieldOffset(0)]publicintfoo;[FieldOffset(0)]publiclongbar;}
#[repr(i*)]
or#[repr(u*)]
definedEnum
is supported.
#[repr(u8)]pubenumByteEnum{A =1,B =2,C =10,}
internalenumByteTest:byte{A=1,B=2,C=10,}
csbindgen supportsbitflags crate.
bitflags!{ #[repr(C)] #[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]structEnumFlags:u32{constA =0b00000001;constB =0b00000010;constC =0b00000100;constABC =Self::A.bits() |Self::B.bits() |Self::C.bits();}}
[Flags]internalenumEnumFlags:uint{A=0b00000001,B=0b00000010,C=0b00000100,ABC=A|B|C,}
You can receive, return function to/from C#.
#[no_mangle]pubextern"C"fncsharp_to_rust(cb:extern"C"fn(x:i32,y:i32) ->i32){let sum =cb(10,20);// invoke C# methodprintln!("{sum}");}#[no_mangle]pubextern"C"fnrust_to_csharp() ->externfn(x:i32,y:i32) ->i32{ sum// return rust method}extern"C"fnsum(x:i32,y:i32) ->i32{ x + y}
In default, csbindgen generatesextern "C" fn
asdelegate* unmanaged[Cdecl]<>
.
[DllImport(__DllName,EntryPoint="csharp_to_rust",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexternvoidcsharp_to_rust(delegate* unmanaged[Cdecl]<int,int,int>cb);[DllImport(__DllName,EntryPoint="rust_to_csharp",CallingConvention=CallingConvention.Cdecl,ExactSpelling=true)]publicstaticexterndelegate* unmanaged[Cdecl]<int,int,int>rust_to_csharp();
It can use in C# like this.
// C# -> Rust, pass static UnmanagedCallersOnly method with `&`[UnmanagedCallersOnly(CallConvs=new[]{typeof(CallConvCdecl)})]staticintSum(intx,inty)=>x+y;NativeMethods.csharp_to_rust(&Sum);// Rust -> C#, get typed delegate*varf=NativeMethods.rust_to_csharp();varv=f(20,30);Console.WriteLine(v);// 50
Unity can not use C# 9.0 function pointer, csbindgen has to use
MonoPInvokeCallback
options. see:Unity Callback section.
Rust FFI suppotsOption<fn>
, it can receive null pointer.
#[no_mangle]pubextern"C"fnnullable_callback_test(cb:Option<extern"C"fn(a:i32) ->i32>) ->i32{match cb{Some(f) =>f(100),None => -1,}}
varv=NativeMethods.nullable_callback_test(null);// -1
Allocated Rust memory in heap can send to C# via pointer andBox::into_raw
andBox::from_raw
.
#[no_mangle]pubextern"C"fncreate_context() ->*mutContext{let ctx =Box::new(Context{foo:true});Box::into_raw(ctx)}#[no_mangle]pubextern"C"fndelete_context(context:*mutContext){unsafe{Box::from_raw(context)};}#[repr(C)]pubstructContext{pubfoo:bool,pubbar:i32,pubbaz:u64}
varcontext=NativeMethods.create_context();// do anything...NativeMethods.delete_context(context);
You can also pass memory allocated by C# to Rust (usefixed
orGCHandle.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 reference, csbindgen generates empty C# struct.
#[no_mangle]pubextern"C"fncreate_counter_context() ->*mutCounterContext{let ctx =Box::new(CounterContext{set:HashSet::new(),});Box::into_raw(ctx)}#[no_mangle]pubunsafeextern"C"fninsert_counter_context(context:*mutCounterContext,value:i32){letmut counter =Box::from_raw(context); counter.set.insert(value);Box::into_raw(counter);}#[no_mangle]pubunsafeextern"C"fndelete_counter_context(context:*mutCounterContext){let counter =Box::from_raw(context);for valuein counter.set.iter(){println!("counter value: {}", value)}}// no repr(C)pubstructCounterContext{pubset:HashSet<i32>,}
// csbindgen generates this handler type[StructLayout(LayoutKind.Sequential)]internalunsafepartialstructCounterContext{}// You can hold pointer instanceCounterContext*ctx=NativeMethods.create_counter_context();NativeMethods.insert_counter_context(ctx,10);NativeMethods.insert_counter_context(ctx,20);NativeMethods.delete_counter_context(ctx);
In this case, recommed to use withGrouping Extension Methods.
If you want to pass null-pointer, in rust side, convert to Option byas_ref()
.
#[no_mangle]pubunsafeextern"C"fnnull_pointer_test(p:*constu8){let ptr =unsafe{ p.as_ref()};match ptr{Some(p2) =>print!("pointer address: {}",*p2),None =>println!("null pointer!"),};}
// in C#, invoke by null.NativeMethods.null_pointer_test(null);
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 asbyte*
in C#.
#[no_mangle]pubextern"C"fnalloc_c_string() ->*mutc_char{let str =CString::new("foo bar baz").unwrap(); str.into_raw()}#[no_mangle]pubunsafeextern"C"fnfree_c_string(str:*mutc_char){unsafe{CString::from_raw(str)};}
// null-terminated `byte*` or sbyte* can materialize by new String()varcString=NativeMethods.alloc_c_string();varstr=newString((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.
#[repr(C)]pubstructByteBuffer{ptr:*mutu8,length:i32,capacity:i32,}implByteBuffer{pubfnlen(&self) ->usize{self.length.try_into().expect("buffer length negative or overflowed")}pubfnfrom_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.");// keep memory until call deleteletmut v = std::mem::ManuallyDrop::new(bytes);Self{ptr: v.as_mut_ptr(), length, capacity,}}pubfnfrom_vec_struct<T:Sized>(bytes:Vec<T>) ->Self{let element_size = std::mem::size_of::<T>()asi32;let length =(bytes.len()asi32)* element_size;let capacity =(bytes.capacity()asi32)* element_size;letmut v = std::mem::ManuallyDrop::new(bytes);Self{ptr: v.as_mut_ptr()as*mutu8, length, capacity,}}pubfndestroy_into_vec(self) ->Vec<u8>{ifself.ptr.is_null(){vec![]}else{let capacity:usize =self.capacity.try_into().expect("buffer capacity negative or overflowed");let length:usize =self.length.try_into().expect("buffer length negative or overflowed");unsafe{Vec::from_raw_parts(self.ptr, length, capacity)}}}pubfndestroy_into_vec_struct<T:Sized>(self) ->Vec<T>{ifself.ptr.is_null(){vec![]}else{let element_size = std::mem::size_of::<T>()asi32;let length =(self.length* element_size)asusize;let capacity =(self.capacity* element_size)asusize;unsafe{Vec::from_raw_parts(self.ptras*mutT, length, capacity)}}}pubfndestroy(self){drop(self.destroy_into_vec());}}
// C# side span utilitypartialstructByteBuffer{publicunsafeSpan<byte>AsSpan(){returnnewSpan<byte>(ptr,length);}publicunsafeSpan<T>AsSpan<T>(){returnMemoryMarshal.CreateSpan(refUnsafe.AsRef<T>(ptr),length/Unsafe.SizeOf<T>());}}
WithByteBuffer
, you can sendVec<>
to C#. the pattern forString
,Vec<u8>
,Vec<i32>
, Rust -> C# is as follows.
#[no_mangle]pubextern"C"fnalloc_u8_string() ->*mutByteBuffer{let str =format!("foo bar baz");let buf =ByteBuffer::from_vec(str.into_bytes());Box::into_raw(Box::new(buf))}#[no_mangle]pubunsafeextern"C"fnfree_u8_string(buffer:*mutByteBuffer){let buf =Box::from_raw(buffer);// drop inner buffer, if you need String, use String::from_utf8_unchecked(buf.destroy_into_vec()) instead. buf.destroy();}#[no_mangle]pubextern"C"fnalloc_u8_buffer() ->*mutByteBuffer{let vec:Vec<u8> =vec![1,10,100];let buf =ByteBuffer::from_vec(vec);Box::into_raw(Box::new(buf))}#[no_mangle]pubunsafeextern"C"fnfree_u8_buffer(buffer:*mutByteBuffer){let buf =Box::from_raw(buffer);// drop inner buffer, if you need Vec<u8>, use buf.destroy_into_vec() instead. buf.destroy();}#[no_mangle]pubextern"C"fnalloc_i32_buffer() ->*mutByteBuffer{let vec:Vec<i32> =vec![1,10,100,1000,10000];let buf =ByteBuffer::from_vec_struct(vec);Box::into_raw(Box::new(buf))}#[no_mangle]pubunsafeextern"C"fnfree_i32_buffer(buffer:*mutByteBuffer){let buf =Box::from_raw(buffer);// drop inner buffer, if you need Vec<i32>, use buf.destroy_into_vec_struct::<i32>() instead. buf.destroy();}
varu8String=NativeMethods.alloc_u8_string();varu8Buffer=NativeMethods.alloc_u8_buffer();vari32Buffer=NativeMethods.alloc_i32_buffer();try{varstr=Encoding.UTF8.GetString(u8String->AsSpan());Console.WriteLine(str);Console.WriteLine("----");varbuffer=u8Buffer->AsSpan();foreach(variteminbuffer){Console.WriteLine(item);}Console.WriteLine("----");vari32Span=i32Buffer->AsSpan<int>();foreach(varitemini32Span){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, usestd::slice::from_raw_parts
to create slice.
#[no_mangle]pubunsafeextern"C"fncsharp_to_rust_string(utf16_str:*constu16,utf16_len:i32){let slice = std::slice::from_raw_parts(utf16_str, utf16_lenasusize);let str =String::from_utf16(slice).unwrap();println!("{}",str);}#[no_mangle]pubunsafeextern"C"fncsharp_to_rust_utf8(utf8_str:*constu8,utf8_len:i32){let slice = std::slice::from_raw_parts(utf8_str, utf8_lenasusize);let str =String::from_utf8_unchecked(slice.to_vec());println!("{}",str);}#[no_mangle]pubunsafeextern"C"fncsharp_to_rust_bytes(bytes:*constu8,len:i32){let slice = std::slice::from_raw_parts(bytes, lenasusize);let vec = slice.to_vec();println!("{:?}", vec);}
varstr="foobarbaz:あいうえお";// ENG:JPN(Unicode, testing for UTF16)fixed(char*p=str){NativeMethods.csharp_to_rust_string((ushort*)p,str.Length);}varstr2=Encoding.UTF8.GetBytes("あいうえお:foobarbaz");fixed(byte*p=str2){NativeMethods.csharp_to_rust_utf8(p,str2.Length);}varbytes=newbyte[]{1,10,100,255};fixed(byte*p=bytes){NativeMethods.csharp_to_rust_bytes(p,bytes.Length);}
Again, the important thing is that memory allocated in Rust must release in Rust and memory allocated in C# must release in C#.
csbindgen silently skips over any method with a non-generatable type. If you build withcargo 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: {}
csbindgen doesn't handle C's variadic arguments, which causes undefined behaviors, because this feature is not stable both in C# and Rust.There is a__arglist
keyword for C's variadic arguments in C#.__arglist
has many problems except Windows environment.There is an issue about C's variadic arguments in Rust.
This library is licensed under the MIT License.
About
Generate C# FFI from Rust for automatically brings native code and C native library to .NET and Unity.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.