using System; using System.Runtime.InteropServices; namespace AlgorithmDllIsolationConsoleApp { class Program { // 导入 C++ DLL 中的 DetectDiamond 函数 [DllImport("diamond_cut_inspector.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr DetectDiamond(string jsonData); // 导入 C++ DLL 中的 FreeMemory 函数 [DllImport("diamond_cut_inspector.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] private static extern void FreeString(IntPtr ptr); static void Main(string[] args) { try { // 从命令行参数获取 JSON 数据 if (args.Length == 0 || string.IsNullOrWhiteSpace(args[0])) { Console.WriteLine("No input data provided."); return; } string jsonData = args[0]; IntPtr resultPtr = IntPtr.Zero; try { // 调用 C++ DLL 函数 resultPtr = DetectDiamond(jsonData); string resultJson = Marshal.PtrToStringAnsi(resultPtr); // 输出结果 if (string.IsNullOrEmpty(resultJson)) { Console.WriteLine("Algorithm failed, no result."); } else { Console.WriteLine(resultJson); } } catch (DllNotFoundException ex) { Console.WriteLine($"DLL not found: {ex.Message}"); } catch (EntryPointNotFoundException ex) { Console.WriteLine($"Entry point not found in DLL: {ex.Message}"); } catch (BadImageFormatException ex) { Console.WriteLine($"Bad image format for DLL: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"An error occurred while calling the DLL: {ex.Message}"); Console.WriteLine($"Stack Trace: {ex.StackTrace}"); } finally { // 确保释放内存 if (resultPtr != IntPtr.Zero) { FreeString(resultPtr); } } } catch (Exception ex) { // 捕获其他可能的异常 Console.WriteLine($"An unexpected error occurred: {ex.Message}"); Console.WriteLine($"Stack Trace: {ex.StackTrace}"); } } } }