|
1 | | -// tests9.rs |
2 | | -// |
3 | | -// Rust is highly capable of sharing FFI interfaces with C/C++ and other statically compiled |
4 | | -// languages, and it can even link within the code itself! It makes it through the extern |
5 | | -// block, just like the code below. |
6 | | -// |
7 | | -// The short string after the `extern` keyword indicates which ABI the externally imported |
8 | | -// function would follow. In this exercise, "Rust" is used, while other variants exists like |
9 | | -// "C" for standard C ABI, "stdcall" for the Windows ABI. |
10 | | -// |
11 | | -// The externally imported functions are declared in the extern blocks, with a semicolon to |
12 | | -// mark the end of signature instead of curly braces. Some attributes can be applied to those |
13 | | -// function declarations to modify the linking behavior, such as #[link_name = ".."] to |
14 | | -// modify the actual symbol names. |
15 | | -// |
16 | | -// If you want to export your symbol to the linking environment, the `extern` keyword can |
17 | | -// also be marked before a function definition with the same ABI string note. The default ABI |
18 | | -// for Rust functions is literally "Rust", so if you want to link against pure Rust functions, |
19 | | -// the whole extern term can be omitted. |
20 | | -// |
21 | | -// Rust mangles symbols by default, just like C++ does. To suppress this behavior and make |
22 | | -// those functions addressable by name, the attribute #[no_mangle] can be applied. |
23 | | -// |
24 | | -// In this exercise, your task is to make the testcase able to call the `my_demo_function` in |
25 | | -// module Foo. the `my_demo_function_alias` is an alias for `my_demo_function`, so the two |
26 | | -// line of code in the testcase should call the same function. |
27 | | -// |
28 | | -// You should NOT modify any existing code except for adding two lines of attributes. |
29 | | - |
30 | | -// I AM NOT DONE |
31 | | - |
32 | 1 | extern "Rust" { |
| 2 | + // 为my_demo_function添加link_name属性,指向Foo::my_demo_function |
| 3 | + #[link_name = "Foo::my_demo_function"] |
33 | 4 | fn my_demo_function(a: u32) -> u32; |
| 5 | + // 为my_demo_function_alias添加link_name属性,同样指向Foo::my_demo_function(别名) |
| 6 | + #[link_name = "Foo::my_demo_function"] |
34 | 7 | fn my_demo_function_alias(a: u32) -> u32; |
35 | 8 | } |
36 | 9 |
|
37 | 10 | mod Foo { |
| 11 | + // 为函数添加no_mangle属性,禁止符号混淆,确保外部能通过名称找到该函数 |
| 12 | + #[no_mangle] |
38 | 13 | // No `extern` equals `extern "Rust"`. |
39 | 14 | fn my_demo_function(a: u32) -> u32 { |
40 | 15 | a |
|
0 commit comments