Ejemplo n.º 1
0
        public void TestAnonymousStructAndFunction()
        {
            var options = new CSharpConverterOptions()
            {
            };

            var csCompilation = CSharpConverter.Convert(@"
struct {
    int a;
    int b;
    void (*ptr)(int arg0, int arg1, void (*arg2)(int arg3));

    union
    {
        int c;
        int d;
    } e;
} outer;
            ", options);

            Assert.False(csCompilation.HasErrors);

            var fs         = new MemoryFileSystem();
            var codeWriter = new CodeWriter(new CodeWriterOptions(fs));

            csCompilation.DumpTo(codeWriter);

            var text = fs.ReadAllText(options.DefaultOutputFilePath);

            Console.WriteLine(text);
        }
Ejemplo n.º 2
0
        private static void GenerateDwarf()
        {
            var cppOptions = new CSharpConverterOptions()
            {
                DefaultClassLib                  = "DwarfNative",
                DefaultNamespace                 = "LibObjectFile.Dwarf",
                DefaultOutputFilePath            = "/LibObjectFile.Dwarf.generated.cs",
                DefaultDllImportNameAndArguments = "NotUsed",
                MappingRules =
                {
                    map => map.MapMacroToConst("^DW_TAG_.*",        "unsigned short"),
                    map => map.MapMacroToConst("^DW_FORM_.*",       "unsigned short"),
                    map => map.MapMacroToConst("^DW_AT_.*",         "unsigned short"),
                    map => map.MapMacroToConst("^DW_LN[ES]_.*",     "unsigned char"),
                    map => map.MapMacroToConst("^DW_IDX_.*",        "unsigned short"),
                    map => map.MapMacroToConst("^DW_LANG_.*",       "unsigned short"),
                    map => map.MapMacroToConst("^DW_ID_.*",         "unsigned char"),
                    map => map.MapMacroToConst("^DW_CC_.*",         "unsigned char"),
                    map => map.MapMacroToConst("^DW_ISA_.*",        "unsigned char"),
                    map => map.MapMacroToConst("^DW_CHILDREN_.*",   "unsigned char"),
                    map => map.MapMacroToConst("^DW_OP_.*",         "unsigned char"),
                    map => map.MapMacroToConst("^DW_ACCESS_.*",     "unsigned char"),
                    map => map.MapMacroToConst("^DW_VIS_.*",        "unsigned char"),
                    map => map.MapMacroToConst("^DW_VIRTUALITY_.*", "unsigned char"),
                    map => map.MapMacroToConst("^DW_INL_.*",        "unsigned char"),
                    map => map.MapMacroToConst("^DW_ORD_.*",        "unsigned char"),
                    map => map.MapMacroToConst("^DW_DSC_.*",        "unsigned char"),
                    map => map.MapMacroToConst("^DW_UT_.*",         "unsigned char"),
                }
            };

            cppOptions.GenerateEnumItemAsFields = false;
            cppOptions.IncludeFolders.Add(Environment.CurrentDirectory);

            var csCompilation = CSharpConverter.Convert(@"#include ""dwarf.h""", cppOptions);

            AssertCompilation(csCompilation);

            // Add pragma
            var csFile = csCompilation.Members.OfType <CSharpGeneratedFile>().First();
            var ns     = csFile.Members.OfType <CSharpNamespace>().First();

            csFile.Members.Insert(csFile.Members.IndexOf(ns), new CSharpLineElement("#pragma warning disable 1591"));

            ProcessEnum(cppOptions, csCompilation, "DW_AT_", "DwarfAttributeKind");
            ProcessEnum(cppOptions, csCompilation, "DW_FORM_", "DwarfAttributeForm");
            ProcessEnum(cppOptions, csCompilation, "DW_TAG_", "DwarfTag");
            ProcessEnum(cppOptions, csCompilation, "DW_OP_", "DwarfOperationKind");
            ProcessEnum(cppOptions, csCompilation, "DW_LANG_", "DwarfLanguageKind");
            ProcessEnum(cppOptions, csCompilation, "DW_CC_", "DwarfCallingConvention");
            ProcessEnum(cppOptions, csCompilation, "DW_UT_", "DwarfUnitKind");

            GenerateDwarfAttributes(ns);
            GenerateDwarfDIE(ns);

            csCompilation.DumpTo(GetCodeWriter(Path.Combine("LibObjectFile", "generated")));
        }
Ejemplo n.º 3
0
        public void TestMacroToConst()
        {
            var options = new CSharpConverterOptions()
            {
                MappingRules =
                {
                    e => e.MapMacroToConst("MYNAME_(.*)",                                       "int"),
                    e => e.MapMacroToEnum("MYNAME_(.*)",                                        "MYNAME_ENUM",@"MYNAME_ENUM_$1"),
                    e => e.Map <CppParameter>("function0::x").Type("char*"),
                    e => e.Map <CppFunction>("function0").Visibility(CSharpVisibility.Private),
                }
            };

            var csCompilation = CSharpConverter.Convert(@"
#ifdef WIN32
#define EXPORT_API __declspec(dllexport)
#else
#define EXPORT_API __attribute__((visibility(""default"")))
#endif
#define MYNAME_X 1
#define MYNAME_Y 2
#define MYNAME_XYWZ 3

EXPORT_API void function0(int x);
            ", options);

            Assert.False(csCompilation.HasErrors);

            var fs         = new MemoryFileSystem();
            var codeWriter = new CodeWriter(new CodeWriterOptions(fs));

            csCompilation.DumpTo(codeWriter);

            var text = fs.ReadAllText(options.DefaultOutputFilePath);

            Console.WriteLine(text);
        }
Ejemplo n.º 4
0
        public void CheckFunction()
        {
            var options = new CSharpConverterOptions()
            {
                GenerateAsInternal   = true,
                TypedefCodeGenKind   = CppTypedefCodeGenKind.Wrap,
                TypedefWrapWhiteList =
                {
                    "git_my_string"
                }
            };

            var csCompilation = CSharpConverter.Convert(@"
            #ifdef WIN32
            #define EXPORT_API __declspec(dllexport)
            #else
            #define EXPORT_API __attribute__((visibility(""default"")))
            #endif

            enum Toto
            {
                TOTO = 0,
                TOTO_FLAG = 1 << 0,
            };

            // This is a comment
            struct Tata
            {
                int a;

                int b;
                int c;
                char items[4];
                int item2[8];

                const char* d;
            };

            struct git_my_repo;

            typedef int git_my_yoyo;

            typedef const char* git_my_string;

            // This is a comment.
            // This is another comment
            // @param myrepo yoyo
            // @return This is a big list of things to return
            EXPORT_API bool function0(git_my_repo* myrepo, int a, float b, const char* text, const char text2[], bool arg4[], git_my_yoyo arg5, git_my_string arg6);
            ", options);

            Assert.False(csCompilation.HasErrors);

            var fs         = new MemoryFileSystem();
            var codeWriter = new CodeWriter(new CodeWriterOptions(fs));

            csCompilation.DumpTo(codeWriter);

            var text = fs.ReadAllText(options.DefaultOutputFilePath);

            Console.WriteLine(text);
        }
Ejemplo n.º 5
0
        private static void GenerateElf()
        {
            var cppOptions = new CSharpConverterOptions()
            {
                DefaultClassLib                  = "ElfNative",
                DefaultNamespace                 = "LibObjectFile.Elf",
                DefaultOutputFilePath            = "/LibObjectFile.Elf.generated.cs",
                DefaultDllImportNameAndArguments = "NotUsed",
                MappingRules =
                {
                    map => map.MapMacroToConst("^EI.*",           "uint8_t"),
                    map => map.MapMacroToConst("^ELFMAG\\d",      "uint8_t"),
                    map => map.MapMacroToConst("^ELFCLASS.*",     "uint8_t"),
                    map => map.MapMacroToConst("^ELFDATA.*",      "uint8_t"),
                    map => map.MapMacroToConst("^ELFOSABI.*",     "uint8_t"),
                    map => map.MapMacroToConst("^ET_.*",          "uint16_t"),
                    map => map.MapMacroToConst("^EM_.*",          "uint16_t"),
                    map => map.MapMacroToConst("^EV_.*",          "uint8_t"),
                    map => map.MapMacroToConst("^SHN_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^SHT_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^SHF_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^EF_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^PT_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^PF_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^NT_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^DT_.*",          "int32_t"),
                    map => map.MapMacroToConst("^DF_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^DTF_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^VER_DEF_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^VER_FLG_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^VER_NDX_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^VER_NEED_.*",    "uint16_t"),
                    map => map.MapMacroToConst("^ELFCOMPRESS_.*", "int32_t"),
                    map => map.MapMacroToConst("^SYMINFO_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^STB_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^STT_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^STN_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^STV_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^R_.*",           "uint32_t"),
                    map => map.MapMacroToConst("ELF_NOTE_OS_.*",  "uint32_t"),
                }
            };

            cppOptions.ConfigureForWindowsMsvc(CppTargetCpu.X86_64);
            cppOptions.Defines.Add("_AMD64_");
            cppOptions.Defines.Add("_TARGET_AMD64_");
            cppOptions.Defines.Add("STARK_NO_ENUM_FLAG");
            cppOptions.GenerateEnumItemAsFields = false;
            cppOptions.IncludeFolders.Add(Environment.CurrentDirectory);

            var csCompilation = CSharpConverter.Convert(@"#include ""elf.h""", cppOptions);

            AssertCompilation(csCompilation);

            // Add pragma
            var csFile = csCompilation.Members.OfType <CSharpGeneratedFile>().First();
            var ns     = csFile.Members.OfType <CSharpNamespace>().First();

            csFile.Members.Insert(csFile.Members.IndexOf(ns), new CSharpLineElement("#pragma warning disable 1591"));

            ProcessElfEnum(cppOptions, csCompilation, "EM_", "ElfArch");
            ProcessElfEnum(cppOptions, csCompilation, "ELFOSABI_", "ElfOSABI");
            ProcessElfEnum(cppOptions, csCompilation, "R_", "ElfRelocationType");
            ProcessElfEnum(cppOptions, csCompilation, "NT_", "ElfNoteType");

            csCompilation.DumpTo(GetCodeWriter(Path.Combine("LibObjectFile", "generated")));
        }
Ejemplo n.º 6
0
        private static void ProcessElfEnum(CSharpConverterOptions cppOptions, CSharpCompilation csCompilation, string enumPrefix, string enumClassName)
        {
            var ns = csCompilation.Members.OfType <CSharpGeneratedFile>().First().Members.OfType <CSharpNamespace>().First();

            var rawElfClass = ns.Members.OfType <CSharpClass>().First();

            var enumRawFields = rawElfClass.Members.OfType <CSharpField>().Where(x => (x.Modifiers & CSharpModifiers.Const) != 0 && x.Name.StartsWith(enumPrefix)).ToList();

            var enumClass = new CSharpStruct(enumClassName)
            {
                Modifiers = CSharpModifiers.Partial | CSharpModifiers.ReadOnly
            };

            ns.Members.Add(enumClass);

            bool isReloc = enumPrefix == "R_";

            var filteredFields = new List <CSharpField>();

            foreach (var enumRawField in enumRawFields)
            {
                var rawName = enumRawField.Name;

                string relocArch = null;

                if (isReloc)
                {
                    foreach (var mapReloc in MapRelocMachineToArch)
                    {
                        if (rawName.StartsWith(mapReloc.Key))
                        {
                            relocArch = mapReloc.Value;
                            break;
                        }
                    }

                    if (relocArch == null)
                    {
                        continue;
                    }
                }

                // NUM fields
                if (rawName.EndsWith("_NUM"))
                {
                    continue;
                }

                filteredFields.Add(enumRawField);

                var csFieldName = isReloc ? rawName : rawName.Substring(enumPrefix.Length); // discard EM_
                if (csFieldName.StartsWith("386"))
                {
                    csFieldName = $"I{csFieldName}";
                }
                else
                {
                    switch (csFieldName)
                    {
                    case "88K":
                        csFieldName = "M88K";
                        break;

                    case "860":
                        csFieldName = "I860";
                        break;

                    case "960":
                        csFieldName = "I960";
                        break;

                    default:
                        // assume Motorola
                        if (csFieldName.StartsWith("68"))
                        {
                            csFieldName = $"M{csFieldName}";
                        }

                        break;
                    }
                }

                if (char.IsDigit(csFieldName[0]))
                {
                    throw new InvalidOperationException($"The enum name `{rawName}` starts with a number and needs to be modified");
                }

                csFieldName = CSharpHelper.EscapeName(csFieldName);

                var enumField = new CSharpField(csFieldName)
                {
                    Modifiers  = CSharpModifiers.Static | CSharpModifiers.ReadOnly,
                    FieldType  = enumClass,
                    Visibility = CSharpVisibility.Public,
                    Comment    = enumRawField.Comment,
                    InitValue  = relocArch != null ?
                                 $"new {enumClass.Name}(ElfArch.{relocArch}, {cppOptions.DefaultClassLib}.{rawName})" :
                                 $"new {enumClass.Name}({cppOptions.DefaultClassLib}.{rawName})"
                };

                enumClass.Members.Add(enumField);
            }

            var toStringInternal = new CSharpMethod()
            {
                Name       = "ToStringInternal",
                Visibility = CSharpVisibility.Private,
                ReturnType = CSharpPrimitiveType.String
            };

            enumClass.Members.Add(toStringInternal);

            toStringInternal.Body = (writer, element) =>
            {
                var values = new HashSet <object>();
                if (isReloc)
                {
                    writer.WriteLine("switch (((ulong)Value << 16) | Arch.Value)");
                }
                else
                {
                    writer.WriteLine("switch (Value)");
                }
                writer.OpenBraceBlock();
                foreach (var rawField in filteredFields)
                {
                    var cppField = ((CppField)rawField.CppElement);
                    if (isReloc)
                    {
                        string relocMachine = null;
                        foreach (var mapReloc in MapRelocMachineToMachine)
                        {
                            if (rawField.Name.StartsWith(mapReloc.Key))
                            {
                                relocMachine = mapReloc.Value;
                                break;
                            }
                        }

                        if (relocMachine == null)
                        {
                            continue;
                        }

                        if (!values.Add(relocMachine + "$" + cppField.InitValue.Value))
                        {
                            continue;
                        }

                        writer.WriteLine($"case ((ulong){cppOptions.DefaultClassLib}.{rawField.Name} << 16) | {cppOptions.DefaultClassLib}.{relocMachine} : return \"{rawField.Name}\";");
                    }
                    else
                    {
                        if (!values.Add(cppField.InitValue.Value))
                        {
                            continue;
                        }

                        string descriptionText = rawField.Name;

                        if (cppField.Comment != null)
                        {
                            descriptionText += " - " + cppField.Comment.ToString().Replace("\"", "\\\"");
                        }
                        descriptionText = descriptionText.Replace("\r\n", "").Replace("\n", "");
                        writer.WriteLine($"case {cppOptions.DefaultClassLib}.{rawField.Name}: return \"{descriptionText}\";");
                    }
                }

                writer.WriteLine($"default: return \"Unknown {enumClassName}\";");
                writer.CloseBraceBlock();
            };
        }
Ejemplo n.º 7
0
        private static int Main(string[] _)
        {
            if (string.IsNullOrWhiteSpace(MlSdkPath))
            {
                Console.WriteLine("No mlsdk environment variable is defined. Make sure you have downloaded the latest magic leap sdk from The Lab, and define this path to the sdk version you wish to use. ex: \"C:\\Users\\your-account\\MagicLeap\\mlsdk\"");
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
                return(1);
            }

            Console.WriteLine($"Found mlsdk at path: {MlSdkPath}");
            //Directory.GetFiles($"{BaseSdkPath}include", "*.h", SearchOption.TopDirectoryOnly).ToList();
            var files = new List <string>
            {
                $"{BaseSdkPath}include\\ml_camera.h",
                $"{BaseSdkPath}include\\ml_camera_metadata.h",
                $"{BaseSdkPath}include\\ml_lifecycle.h",
                $"{BaseSdkPath}include\\ml_graphics.h",
                $"{BaseSdkPath}include\\ml_graphics_utils.h",
                $"{BaseSdkPath}include\\ml_input.h",
                $"{BaseSdkPath}include\\ml_logging.h",
                $"{BaseSdkPath}include\\ml_movement.h",
                $"{BaseSdkPath}include\\ml_controller.h",
                $"{BaseSdkPath}include\\ml_aruco_tracking.h",
                $"{BaseSdkPath}include\\ml_cv_camera.h",
                $"{BaseSdkPath}include\\ml_data_array.h",
                $"{BaseSdkPath}include\\ml_eye_tracking.h",
                $"{BaseSdkPath}include\\ml_found_object.h",
                $"{BaseSdkPath}include\\ml_hand_meshing.h",
                $"{BaseSdkPath}include\\ml_hand_tracking.h",
                $"{BaseSdkPath}include\\ml_head_tracking.h",
                $"{BaseSdkPath}include\\ml_image_tracking.h",
                $"{BaseSdkPath}include\\ml_lighting_tracking.h",
                $"{BaseSdkPath}include\\ml_meshing2.h",
                $"{BaseSdkPath}include\\ml_perception.h",
                $"{BaseSdkPath}include\\ml_persistent_coordinate_frames.h",
                $"{BaseSdkPath}include\\ml_planes.h",
                $"{BaseSdkPath}include\\ml_raycast.h",
                $"{BaseSdkPath}include\\ml_snapshot.h",
            };

            var csOptions = new CSharpConverterOptions
            {
                GenerateAsInternal               = true,
                GenerateEnumItemAsFields         = true,
                DispatchOutputPerInclude         = true,
                DefaultDllImportNameAndArguments = "ERROR",
                MappingRules =
                {
                    // DllImportLibrary in later version of CppAst.CodeGen
                    //e => e.Map("*").DllImportLibrary("\"ml_camera\"", "ml_camera.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_camera_metadata\"", "ml_camera_metadata.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_lifecycle\"", "ml_lifecycle.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_lifecycle\"", "ml_fileinfo.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_graphics\"", "ml_graphics.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_graphics_utils\"", "ml_graphics_utils.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_input\"", "ml_input.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_ext_logging\"", "ml_logging.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_movement\"", "ml_movement.h"),

                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_controller.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_aruco_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_cv_camera.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_data_array.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_eye_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_found_object.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_hand_meshing.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_hand_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_head_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_image_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_lighting_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_meshing2.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_perception.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_persistent_coordinate_frames.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_planes.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_raycast.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_snapshot.h"),

                    //e => e.Map("*").DllImportLibrary("\"ml_audio\"", "ml_audio.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_app_connect\"", "ml_app_connect.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_avatar\"", "ml_avatar.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth_adapter\"", "ml_bluetooth_adapter.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth_gatt\"", "ml_bluetooth_gatt.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth_le\"", "ml_bluetooth_le.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth\"", "ml_bluetooth.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_connections\"", "ml_connections.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_contacts\"", "ml_contacts.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_dca\"", "ml_dca.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_dispatch\"", "ml_dispatch.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_identity\"", "ml_identity.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_identity\"", "ml_token_identity.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_locale\"", "ml_locale.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_location\"", "ml_location.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_media_ccparser\"", "ml_media_cea608_caption.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_media_ccparser\"", "ml_media_cea708_caption.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacodec\"", "ml_mediacodec.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacodeclist\"", "ml_mediacodeclist.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacrypto\"", "ml_media_crypto.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_media_data_source\"", "ml_media_data_source.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediadrm\"", "ml_media_drm.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaerror\"", "ml_media_error.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaextractor\"", "ml_media_extractor.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaformat\"", "ml_media_format.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaplayer\"", "ml_media_player.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediastream_source\"", "ml_mediastream_source.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacodec\"", "ml_media_surface_texture.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_musicservice_provider\"", "ml_musicservice_provider.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_musicservice\"", "ml_music_service.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_networking\"", "ml_networking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_platform\"", "ml_platform.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_privileges\"", "ml_privilege_functions.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_purchase\"", "ml_purchase.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_remote\"", "ml_remote.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_screens\"", "ml_screens.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_secure_storage\"", "ml_secure_storage.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_sharedfile\"", "ml_sharedfile.h"),
                }
            };

            var csCompilation = CSharpConverter.Convert(files, csOptions);

            if (csCompilation.HasErrors)
            {
                foreach (var message in csCompilation.Diagnostics.Messages)
                {
                    Console.Error.WriteLine(message);
                }

                Console.Error.WriteLine("Unexpected parsing errors");
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
                return(1);
            }

            var fileSystem = new PhysicalFileSystem();

            csCompilation.DumpTo(
                new CodeWriter(
                    new CodeWriterOptions(
                        new SubFileSystem(fileSystem, fileSystem.ConvertPathFromInternal(OUTPUT_DIRECTORY)))));

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
            return(0);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Generates the PInvoke layer from Monocypher C header files.
        /// - Raw functions
        /// - The same functions using Span&lt;T&gt; when possible
        /// </summary>
        public void GeneratePInvoke()
        {
            var srcFolder  = Path.Combine(MonocypherFolder, "src");
            var destFolder = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\Monocypher"));

            if (!Directory.Exists(srcFolder))
            {
                throw new DirectoryNotFoundException($"The source folder `{srcFolder}` doesn't exist");
            }
            if (!Directory.Exists(destFolder))
            {
                throw new DirectoryNotFoundException($"The destination folder `{destFolder}` doesn't exist");
            }


            var marshalNoFreeNative = new CSharpMarshalAttribute(CSharpUnmanagedKind.CustomMarshaler)
            {
                MarshalTypeRef = "typeof(UTF8MarshallerNoFree)"
            };

            var csOptions = new CSharpConverterOptions()
            {
                DefaultClassLib                  = "Monocypher",
                DefaultNamespace                 = "Monocypher",
                DefaultOutputFilePath            = "/Monocypher.generated.cs",
                DefaultDllImportNameAndArguments = "MonocypherDll",
                GenerateAsInternal               = false,
                DispatchOutputPerInclude         = false,

                MappingRules =
                {
                    e => e.Map <CppField>("crypto_blake2b_vtable").Discard(),
                    e => e.Map <CppField>("crypto_sha512_vtable").Discard(),
                }
            };

            csOptions.Plugins.Insert(0, new FixedArrayTypeConverter());
            csOptions.IncludeFolders.Add(srcFolder);
            var files = new List <string>()
            {
                Path.Combine(srcFolder, "monocypher.h"),
                Path.Combine(srcFolder, "optional", "monocypher-ed25519.h"),
            };

            var csCompilation = CSharpConverter.Convert(files, csOptions);

            if (csCompilation.HasErrors)
            {
                foreach (var message in csCompilation.Diagnostics.Messages)
                {
                    Console.Error.WriteLine(message);
                }
                Console.Error.WriteLine("Unexpected parsing errors");
                Environment.Exit(1);
            }


            var monocypher = csCompilation.Members.OfType <CSharpGeneratedFile>().First().Members.OfType <CSharpNamespace>().First().Members.OfType <CSharpClass>().First();

            ProcessInvokeFunctions(monocypher);

            var fs = new PhysicalFileSystem();

            {
                var subfs      = new SubFileSystem(fs, fs.ConvertPathFromInternal(destFolder));
                var codeWriter = new CodeWriter(new CodeWriterOptions(subfs));
                csCompilation.DumpTo(codeWriter);
            }
        }