Skip to content

Commit 027e359

Browse files
authored
Add error handling and string test for C# interop (#3658)
1 parent ccc0285 commit 027e359

File tree

4 files changed

+39
-5
lines changed

4 files changed

+39
-5
lines changed

crates/samples/csharp/client/client.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,10 @@
33
[DllImport("csharp_component.dll", PreserveSig = false)]
44
static extern uint Add(uint left, uint right);
55

6-
Console.WriteLine("result = {0:D}", Add(4, 5));
6+
Console.WriteLine("Add: {0}", Add(4, 5));
7+
8+
[DllImport("csharp_component.dll", PreserveSig = false)]
9+
[return: MarshalAs(UnmanagedType.BStr)]
10+
static extern string Concat([MarshalAs(UnmanagedType.LPWStr)] string left, [MarshalAs(UnmanagedType.LPWStr)] string right);
11+
12+
Console.WriteLine("Concat: {0}", Concat("hello ", "world"));

crates/samples/csharp/client/src/lib.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ fn test() {
1212
panic!("{}", String::from_utf8_lossy(&output.stderr));
1313
}
1414

15-
let result = String::from_utf8_lossy(&output.stdout).to_string();
16-
assert_eq!(result.trim(), "result = 9");
15+
let result = String::from_utf8_lossy(&output.stdout);
16+
let result: Vec<&str> = result.lines().collect();
17+
18+
assert_eq!(result, ["Add: 9", "Concat: hello world"]);
1719
}

crates/samples/csharp/component/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,6 @@ edition = "2021"
55

66
[lib]
77
crate-type = ["cdylib"]
8+
9+
[dependencies]
10+
windows-core = { workspace = true }
Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,28 @@
1+
use windows_core::*;
2+
3+
pub const S_OK: HRESULT = HRESULT(0);
4+
pub const E_POINTER: HRESULT = HRESULT(0x80004003_u32 as _);
5+
16
#[no_mangle]
2-
unsafe extern "system" fn Add(left: u32, right: u32, result: *mut u32) -> i32 {
7+
unsafe extern "system" fn Add(left: u32, right: u32, result: *mut u32) -> HRESULT {
8+
if result.is_null() {
9+
return E_POINTER;
10+
}
11+
312
*result = left + right;
4-
0 // S_OK
13+
S_OK
14+
}
15+
16+
#[no_mangle]
17+
unsafe extern "system" fn Concat(left: PCWSTR, right: PCWSTR, result: *mut BSTR) -> HRESULT {
18+
if left.is_null() || right.is_null() || result.is_null() {
19+
return E_POINTER;
20+
}
21+
22+
let left = left.as_wide();
23+
let right = right.as_wide();
24+
let combined: Vec<u16> = [left, right].concat();
25+
26+
*result = BSTR::from_wide(&combined);
27+
S_OK
528
}

0 commit comments

Comments
 (0)