-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cs
More file actions
60 lines (54 loc) · 1.94 KB
/
Copy pathmain.cs
File metadata and controls
60 lines (54 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Runtime.InteropServices;
class Where_java
{
[UnmanagedCallersOnly(EntryPoint = "Find_java")]
// <summary>
// 这个函数是 C# 端暴露给 Rust 调用的接口,功能是寻找java,名字叫 Find_java。
// </summary>
public static IntPtr Find_java()
{
List<string> allJavaPaths = [];
// 这是我们用来存储所有找到的 Java 路径的列表,最终会合并成一个字符串返回给 Rust。
List<string> javaHome = GetJavaHomeFromEnvironment();
//
MergePathsWithoutDuplicates
(
allJavaPaths,
javaHome
);
if (allJavaPaths.Count == 0)
{
return Marshal.StringToHGlobalAnsi("NOT_FOUND");
}
string combinedPaths = string.Join("\n", allJavaPaths);
return Marshal.StringToHGlobalAnsi(combinedPaths);
}
/// <summary>
/// 获取 Java 的安装路径 这是最优先的方法, 通过环境变量 JAVA_HOME 获取 Java 的安装路径。
/// </summary>
/// <returns>Java 安装路径的列表</returns>
public static List<string> GetJavaHomeFromEnvironment()
{
List<string> Paths = [];
string? javaHome = Environment.GetEnvironmentVariable("JAVA_HOME");
if (!string.IsNullOrEmpty(javaHome) && !Paths.Contains(javaHome))
{
Paths.Add(javaHome);
}
return (Paths);
}
/// <summary>
/// 💡 辅助小工具:将新找到的路径列表安全地合并到总清单中,并自动去重
/// </summary>
private static void MergePathsWithoutDuplicates(List<string> targetList, List<string> sourceList)
{
foreach (string path in sourceList)
{
// 还记得我们刚学到的 Contains 吗?如果总清单里没有,才加进去!
if (!targetList.Contains(path))
{
targetList.Add(path);
}
}
}
}