ralfbiedert / interoptopus

The polyglot bindings generator for your library (C#, C, Python, …) 🐙
302 stars 27 forks source link

Question,How to be compatible with string encoding in c# and rust #69

Closed fankaiLiu closed 1 year ago

fankaiLiu commented 1 year ago

I am new to rust ,c# string encoding is unicode and rust is uft-8. but I don't know how to handle them. I want to modify string in rust side, and read it in c#

rust code

use std::ffi::{CStr, CString};
use std::fmt::{Display, Formatter, Pointer};
use interoptopus::patterns::result::FFIError;
use interoptopus::patterns::slice::FFISlice;
use interoptopus::{
    ffi_function, ffi_service, ffi_type, function, pattern, Inventory, InventoryBuilder,
};
use interoptopus::{ffi_service_ctor, ffi_service_method};
use libc::c_char;

....

#[ffi_type]
#[repr(C)]
pub struct FLText {
    pub id: u64,
    pub text: *const c_char,
}

#[ffi_function]
pub  extern "C"  fn test_return_str(mut fltext:FLText) -> FLText {
    let c_str = unsafe {
        assert!(!fltext.text.is_null());
        CStr::from_ptr(fltext.text)
    };
    let r_str = c_str.to_str().unwrap().to_string();
    let r_str=r_str.as_bytes();
    // let a_unicode='の'.escape_unicode();
    fltext.text = CString::new(r_str).unwrap().into_raw();
    fltext
}

c# code

                var flText = new FLText();
                string flStr = "你好";
                flText.id = 123123;
                flText.text = GCHandle.Alloc(flStr.ToArray(), GCHandleType.Pinned).AddrOfPinnedObject();
                var result = x.TestReturnStr(flText);
                var resultStr = Marshal.PtrToStringAuto(result.text);

Thanks for advice~