### Configuring Driver Options in Setup Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md Implement the `Setup` method to configure Clang parsing options, including include directories, headers, libraries, and generator settings like output language and namespace. ```csharp void Setup(Driver driver) { var options = driver.Options; options.GeneratorKind = GeneratorKind.CSharp; var module = options.AddModule("Sample"); module.IncludeDirs.Add(@"C:\Sample\include"); module.Headers.Add("Sample.h"); module.LibraryDirs.Add(@"C:\Sample\lib"); module.Libraries.Add("Sample.lib"); } ``` -------------------------------- ### Install Linux Build Tools Source: https://github.com/mono/cppsharp/wiki/Getting-started Installs necessary build tools for compiling on Linux, including CMake, Ninja, and essential build utilities. ```shell sudo apt-get install cmake ninja-build build-essential ``` -------------------------------- ### Setup FunctionToInstanceMethodPass Source: https://context7.com/mono/cppsharp/llms.txt Enables the FunctionToInstanceMethodPass to promote C free functions with a class pointer as the first parameter to instance methods. This pass should be added to the translation unit passes. ```csharp using CppSharp.Passes; // C++ input: // class Foo { public: int a; }; // int FooAdd(Foo* foo); <- first param is Foo*, becomes Foo.Add() // void FooReset(Foo* foo); <- becomes Foo.Reset() public void SetupPasses(Driver driver) { driver.Context.TranslationUnitPasses.AddPass(new FunctionToInstanceMethodPass()); } // Before pass: generated C# would have // public static int FooAdd(Foo foo) { ... } // on a static helper class // After pass: generated C# has // public partial class Foo { // public int Add() { ... } // FooAdd promoted to instance method // public void Reset() { ... } // FooReset promoted to instance method // } ``` -------------------------------- ### Install Mono Development Package Source: https://github.com/mono/cppsharp/wiki/Getting-started Installs the necessary Mono development package on Ubuntu systems. Ensure you have a recent version of Mono (.NET 4.5) installed. ```shell sudo apt-get install mono-devel ``` -------------------------------- ### Configure CppSharp Driver Options Source: https://github.com/mono/cppsharp/wiki/Getting-started Implement the Setup method of ILibrary to configure CppSharp's driver options. Specify output language, library name, headers, and libraries to be processed. ```csharp void Setup(Driver driver) { var options = driver.Options; options.GeneratorKind = GeneratorKind.CSharp; options.LibraryName = "Sample"; options.Headers.Add("Sample.h"); options.Libraries.Add("Sample.lib"); } ``` -------------------------------- ### Build LLVM using build script Source: https://github.com/mono/cppsharp/blob/main/docs/LLVM.md Use this script to clone, build, and package LLVM for CppSharp. Ensure Git, CMake, and Ninja are installed. An optional --platform flag can specify the build architecture. ```bash ./build.sh clone_llvm ./build.sh build_llvm ./build.sh package_llvm ``` -------------------------------- ### Setup Custom Passes for CppSharp Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md Add custom passes to the CppSharp driver to modify generated code. This example renames uppercase declarations and converts functions to instance methods. ```csharp void SetupPasses(Driver driver) { driver.Context.TranslationUnitPasses.RenameDeclsUpperCase(RenameTargets.Any); driver.Context.TranslationUnitPasses.AddPass(new FunctionToInstanceMethodPass()); } ``` -------------------------------- ### Compile LLVM on Windows (64-bit) Source: https://github.com/mono/cppsharp/wiki/Getting-started Use this command to compile LLVM with Visual Studio 12 for 64-bit binaries. Ensure LLVM targets only X86 and disables examples, docs, and tests. ```shell cd \deps\llvm\build cmake -G "Visual Studio 12 Win64" -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false -DCLANG_INCLUDE_DOCS=false -DCLANG_BUILD_EXAMPLES=false -DLLVM_TARGETS_TO_BUILD="X86" -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false .. msbuild LLVM.sln /p:Configuration=RelWithDebInfo;Platform=x64 /m ``` -------------------------------- ### Setup GetterSetterToPropertyPass Source: https://context7.com/mono/cppsharp/llms.txt Adds the GetterSetterToPropertyPass to convert C++ getter/setter pairs into .NET properties. Control the detection mode to adjust conversion aggressiveness. ```csharp using CppSharp.Passes; // C++ input: // class Foo { // int getValue() const; // void setValue(int v); // bool isEnabled() const; // }; public void SetupPasses(Driver driver) { var pass = new GetterSetterToPropertyPass(); driver.Context.TranslationUnitPasses.AddPass(pass); // Control detection mode — how aggressively to convert methods to properties: // PropertyDetectionMode.All — convert all compatible methods // PropertyDetectionMode.Keywords — only methods starting with get/set/is/has // PropertyDetectionMode.Dictionary — uses an English verb dictionary (default heuristic) // PropertyDetectionMode.None — disable conversion entirely } // Generated C# output with the pass enabled: // public int Value { get; set; } // from getValue() / setValue() // public bool IsEnabled { get; } // from isEnabled() (getter only) ``` -------------------------------- ### Compile LLVM on Windows (32-bit) Source: https://github.com/mono/cppsharp/wiki/Getting-started Use this command to compile LLVM with Visual Studio 12 for 32-bit binaries. Ensure LLVM targets only X86 and disables examples, docs, and tests. ```shell cd \deps\llvm\build cmake -G "Visual Studio 12" -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false -DCLANG_INCLUDE_DOCS=false -DCLANG_BUILD_EXAMPLES=false -DLLVM_TARGETS_TO_BUILD="X86" -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false .. msbuild LLVM.sln /p:Configuration=RelWithDebInfo;Platform=Win32 /m ``` -------------------------------- ### Verbose Build Commands on macOS/Linux Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md To get more detailed output during the build process on macOS/Linux, use the 'verbose=true' flag with make and the '-verbosity:detailed' option with msbuild. ```shell make -C gmake config=release_x64 verbose=true ``` ```shell msbuild CppSharp.sln -p:Configuration=Release -p:Platform=x64 -verbosity:detailed ``` -------------------------------- ### Compile LLVM on Linux Source: https://github.com/mono/cppsharp/wiki/Getting-started Configures and builds LLVM on Linux using CMake and Ninja. It disables examples, documentation, and tests, targeting the X86 architecture. ```shell cd deps/llvm/build cmake -G Ninja -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false -DCLANG_INCLUDE_DOCS=false -DCLANG_BUILD_EXAMPLES=false -DLLVM_TARGETS_TO_BUILD="X86" -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false .. ninja ``` -------------------------------- ### Generated .NET Struct for Foo Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md This is an example of the .NET struct generated after applying the `Postprocess` customizations. It reflects changes like value type semantics and renamed members. ```csharp public unsafe partial struct Foo { [StructLayout(LayoutKind.Explicit, Size = 8)] public struct Internal { [FieldOffset(0)] public int a; [SuppressUnmanagedCodeSecurity] [DllImport("Sample.Native", CallingConvention = CallingConvention.ThisCall, EntryPoint="??0Foo@@QAE@XZ")] public static extern System.IntPtr Foo0(System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("Sample.Native", CallingConvention = CallingConvention.Cdecl, EntryPoint="?FooAdd@@YAHPAVFoo@@@Z")] public static extern int Calc0(System.IntPtr instance); } internal Foo(Foo.Internal* native) : this(new System.IntPtr(native)) { } internal Foo(Foo.Internal native) : this(&native) { } internal Foo(System.IntPtr native) { var _ptr = (Internal*)native.ToPointer(); A = _ptr->a; } internal Internal ToInternal() { var _native = new Foo.Internal(); _native.a = A; return _native; } internal void FromInternal(Internal* native) { var _ptr = native; A = _ptr->a; } public int A; public int Calc() { var _instance = ToInternal(); var ret = Internal.Calc0(new System.IntPtr(&_instance)); FromInternal(&_instance); return ret; } } ``` -------------------------------- ### Generated C# Class with Customizations Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md Example of a C# class generated by CppSharp after applying custom passes. It includes properties, methods, and interop details. ```csharp public unsafe partial class Foo : IDisposable { [StructLayout(LayoutKind.Explicit, Size = 8)] public struct Internal { [FieldOffset(0)] public int a; [FieldOffset(4)] public float b; [SuppressUnmanagedCodeSecurity] [DllImport("Sample.Native", CallingConvention = CallingConvention.ThisCall, EntryPoint="??0Foo@@QAE@XZ")] public static extern System.IntPtr Foo0(System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("Sample.Native", CallingConvention = CallingConvention.Cdecl, EntryPoint="?FooAdd@@YAHPAVFoo@@@Z")] public static extern int Add0(System.IntPtr instance); } public System.IntPtr _Instance { get; protected set; } internal Foo(Foo.Internal* native) : this(new System.IntPtr(native)) { } internal Foo(Foo.Internal native) : this(&native) { } internal Foo(System.IntPtr native) { _Instance = native; } public Foo() { _Instance = Marshal.AllocHGlobal(8); Internal.Foo0(_Instance); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Marshal.FreeHGlobal(_Instance); } public int A { get { var _ptr = (Internal*)_Instance.ToPointer(); return _ptr->a; } set { var _ptr = (Internal*)_Instance.ToPointer(); _ptr->a = value; } } public float B { get { var _ptr = (Internal*)_Instance.ToPointer(); return _ptr->b; } set { var _ptr = (Internal*)_Instance.ToPointer(); _ptr->b = value; } } public int Add() { var ret = Internal.Add0(_Instance); return ret; } } ``` -------------------------------- ### Setup RenameDeclsUpperCase and Prefix Removal Passes Source: https://context7.com/mono/cppsharp/llms.txt Configures passes to rename declarations to UpperCamelCase and remove common C library prefixes. Ensure these passes are added to the translation unit passes. ```csharp using CppSharp.Passes; public void SetupPasses(Driver driver) { var passes = driver.Context.TranslationUnitPasses; // Rename all declarations (functions, classes, methods, fields) to UpperCamelCase passes.RenameDeclsUpperCase(RenameTargets.Any); // Remove a common C library prefix from all matching declarations passes.RemovePrefix("SDL_"); passes.RemovePrefix("SCANCODE_"); // Regex-based renaming: rename declarations matching a regex pattern passes.AddPass(new RegexRenamePass( "^my_lib_(.*)", // match pattern "$1", // replacement (capture group 1 = name without prefix) RenameTargets.Function | RenameTargets.Method )); } ``` -------------------------------- ### Launch CppSharp Generation Pipeline with ConsoleDriver.Run Source: https://context7.com/mono/cppsharp/llms.txt Use ConsoleDriver.Run as the top-level entry point to instantiate the driver, execute ILibrary lifecycle methods, run passes, and generate output files. ```csharp using CppSharp; // Minimal usage: just run with your ILibrary implementation ConsoleDriver.Run(new SampleLibrary()); // The pipeline executed internally: // 1. driver.Setup() -> calls ILibrary.Setup(driver) // 2. driver.SetupPasses() -> calls ILibrary.SetupPasses(driver) // 3. driver.ProcessCode() -> parses headers, runs Preprocess, executes passes, runs Postprocess // 4. driver.GenerateCode() -> invokes the selected generator backend // 5. driver.SaveCode() -> writes generated files to OutputDir ``` -------------------------------- ### Generate Makefiles and Build CppSharp Source: https://github.com/mono/cppsharp/wiki/Getting-started Generates the build system using premake5 and then compiles CppSharp in release_x64 configuration. Navigate to the CppSharp build directory before running these commands. ```shell cd /build ./premake5-linux gmake make -C gmake config=release_x64 ``` -------------------------------- ### Download LLVM and Clang packages Source: https://github.com/mono/cppsharp/blob/main/docs/LLVM.md Automatically download pre-compiled LLVM and Clang packages using the build script. This is an alternative to compiling from source. ```bash cd \build ./build.sh download_llvm ``` -------------------------------- ### Running the CppSharp Console Driver Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md Initiate the binding generation process by calling `ConsoleDriver.Run` with an instance of your custom `ILibrary` implementation. ```csharp ConsoleDriver.Run(new SampleLibrary()); ``` -------------------------------- ### Generated C# Binding for Free Functions Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md Free functions from the native code are grouped into a static class, typically named after the library and file. This example shows the binding for `FooAdd`. ```csharp public partial class SampleSample { public struct Internal { [SuppressUnmanagedCodeSecurity] [DllImport("Sample.Native", CallingConvention = CallingConvention.Cdecl, EntryPoint="?FooAdd@@YAHPAVFoo@@@Z")] public static extern int FooAdd0(System.IntPtr foo); } public static int FooAdd(Foo foo) { var arg0 = foo._Instance; var ret = Internal.FooAdd0(arg0); return ret; } } ``` -------------------------------- ### Generate Makefiles and VS Solution on macOS/Linux Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md Generate the build files, including makefiles and Visual Studio solution, for CppSharp on macOS or Linux. Execute this command from the \\build directory. ```shell cd \build ./build.sh generate -configuration Release -platform x64 ``` -------------------------------- ### Generated C# Binding for Foo Class Source: https://github.com/mono/cppsharp/blob/main/docs/GeneratingBindings.md This is an example of the C# code generated by CppSharp for a native C++ class. It includes interop structures, constructors, disposal, and property accessors. ```csharp public unsafe partial class Foo : IDisposable { [StructLayout(LayoutKind.Explicit, Size = 8)] public struct Internal { [FieldOffset(0)] public int a; [FieldOffset(4)] public float b; [SuppressUnmanagedCodeSecurity] [DllImport("Sample.Native", CallingConvention = CallingConvention.ThisCall, EntryPoint="??0Foo@@QAE@XZ")] public static extern System.IntPtr Foo0(System.IntPtr instance); } public System.IntPtr _Instance { get; protected set; } internal Foo(Foo.Internal* native) : this(new System.IntPtr(native)) { } internal Foo(Foo.Internal native) : this(&native) { } internal Foo(System.IntPtr native) { _Instance = native; } public Foo() { _Instance = Marshal.AllocHGlobal(8); Internal.Foo0(_Instance); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Marshal.FreeHGlobal(_Instance); } public int a { get { var _ptr = (Internal*)_Instance.ToPointer(); return _ptr->a; } set { var _ptr = (Internal*)_Instance.ToPointer(); _ptr->a = value; } } public float b { get { var _ptr = (Internal*)_Instance.ToPointer(); return _ptr->b; } set { var _ptr = (Internal*)_Instance.ToPointer(); _ptr->b = value; } } } ``` -------------------------------- ### Run Test Suite Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md Execute the CppSharp test suite by running the test.sh script from the \\build directory. ```shell ./test.sh ``` -------------------------------- ### Configure CppSharp Binding Generation with ILibrary Source: https://context7.com/mono/cppsharp/llms.txt Implement the ILibrary interface to control the binding generation pipeline. Configure driver/parser options, module settings, and AST transformation passes. ```csharp using CppSharp; using CppSharp.AST; using CppSharp.Generators; using CppSharp.Passes; public class SampleLibrary : ILibrary { public void Setup(Driver driver) { var options = driver.Options; // Choose output language: CSharp (P/Invoke) or CLI options.GeneratorKind = GeneratorKind.CSharp; options.OutputDir = "generated"; var module = options.AddModule("Sample"); module.IncludeDirs.Add(@"C:\Sample\include"); module.Headers.Add("Sample.h"); module.LibraryDirs.Add(@"C:\Sample\lib"); module.Libraries.Add("Sample.lib"); // Configure parser target triple driver.ParserOptions.TargetTriple = "x86_64-pc-win32-msvc"; } public void SetupPasses(Driver driver) { // Rename all declarations to UpperCamelCase (.NET convention) driver.Context.TranslationUnitPasses.RenameDeclsUpperCase(RenameTargets.Any); // Promote free functions whose first param is a class ptr to instance methods driver.Context.TranslationUnitPasses.AddPass(new FunctionToInstanceMethodPass()); // Convert getter/setter pairs to .NET properties driver.Context.TranslationUnitPasses.AddPass(new GetterSetterToPropertyPass()); } public void Preprocess(Driver driver, ASTContext ctx) { // Ignore specific enumerations ctx.IgnoreEnumWithMatchingItem("DUMMY_ENUM_VALUE"); // Generate a .NET enum from C macros matching the given pattern ctx.GenerateEnumFromMacros("InitFlags", "SDL_INIT_(.*)").SetFlags(); // Mark a parameter as 'out' ctx.SetFunctionParameterUsage("SDL_PollEvent", 1, ParameterUsage.Out); // Ignore specific headers ctx.IgnoreHeadersWithName("SDL_atomic*"); } public void Postprocess(Driver driver, ASTContext ctx) { // Change class to a .NET value type (struct) ctx.SetClassAsValueType("Foo"); // Rename a free function in the output ctx.SetNameOfFunction("FooAdd", "FooCalc"); // Drop a field from the generated bindings ctx.IgnoreClassField("Foo", "b"); // Rename a namespace ctx.RenameNamespace("OldNS", "NewNS"); } } // Entry point — runs the full generation pipeline class Program { static void Main(string[] args) => ConsoleDriver.Run(new SampleLibrary()); } // Output: generated/Sample.cs with managed wrappers for all exported symbols ``` -------------------------------- ### Build VS Solution Manually on macOS/Linux Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md Alternatively, on macOS/Linux, you can manually build the generated Visual Studio solution using msbuild after generating the build files. ```shell msbuild CppSharp.sln -p:Configuration=Release -p:Platform=x64 ``` -------------------------------- ### Configure CppSharp Driver Options Source: https://context7.com/mono/cppsharp/llms.txt Set up driver and parser options in C# code to control module definitions, output targets, and generator settings. Ensure correct paths and library names are provided. ```csharp using CppSharp; using CppSharp.Generators; void Setup(Driver driver) { var options = driver.Options; // Select output backend options.GeneratorKind = GeneratorKind.CSharp; // or GeneratorKind.CLI options.OutputDir = Path.Combine(Directory.GetCurrentDirectory(), "bindings"); // Add a module (one module = one output assembly's worth of bindings) var module = options.AddModule("MyLib"); module.SharedLibraryName = "MyLib"; // name of .dll/.so to P/Invoke into module.OutputNamespace = "MyLib.Native"; module.IncludeDirs.Add("/path/to/headers"); module.Headers.Add("MyLib.h"); module.LibraryDirs.Add("/path/to/lib"); module.Libraries.Add("MyLib"); // links MyLib.lib / libMyLib.so // Enable template code generation (experimental) options.GenerateClassTemplates = true; // Set string encoding (default: ASCII for char*, UTF-16/32 for wchar_t*) options.Encoding = System.Text.Encoding.UTF8; // Parser options var parserOptions = driver.ParserOptions; parserOptions.TargetTriple = "x86_64-apple-darwin"; // macOS 64-bit parserOptions.LanguageVersion = LanguageVersion.CPP17; parserOptions.EnableRTTI = false; parserOptions.Verbose = false; parserOptions.AddDefines("MY_PLATFORM_MACOS"); parserOptions.AddArguments("-std=c++17"); } ``` -------------------------------- ### Generate Bindings via CppSharp CLI Tool Source: https://context7.com/mono/cppsharp/llms.txt Use the CppSharp.CLI executable to generate bindings from the command line. Specify paths, libraries, generator kind, and platform as flags. ```shell # Generate C# P/Invoke bindings for a single header on Windows x64 CppSharp.CLI.exe \ -I "C:\MyLib\include" \ -l MyLib \ -L "C:\MyLib\lib" \ -o "C:\output\MyLib" \ --on MyLib.Native \ --gen csharp \ --platform win \ --arch x64 \ C:\MyLib\include\MyLib.h ``` ```shell # Generate C++/CLI bindings for multiple headers using a glob CppSharp.CLI.exe -I ./include -l MyLib -L ./lib -o ./out --gen cli --platform win --arch x64 ./include/*.h ``` ```shell # Generate bindings for all .h files in a folder (auto-discovers headers) CppSharp.CLI.exe -I ./include -l MyLib -L ./lib -o ./out --gen csharp --platform linux --arch x64 ./include ``` ```shell # Multi-library binding with automatic symbol-to-library resolution CppSharp.CLI.exe \ -I ./include \ -l LibA -l LibB \ -L ./lib \ -o ./out \ --gen csharp --platform osx --arch x64 \ --checksymbols \ ./include/LibA.h ./include/LibB.h ``` ```shell # Unity build: one output file per header CppSharp.CLI.exe -I ./inc -l MyLib -L ./lib -o ./out --gen csharp --platform win --arch x64 --unity ./inc/*.h ``` ```shell # Emscripten/WASM target CppSharp.CLI.exe -I ./inc -l MyLib -L ./lib -o ./out --gen csharp --platform emscripten --arch wasm32 ./inc/MyLib.h ``` -------------------------------- ### Run CppSharp Test Source: https://github.com/mono/cppsharp/wiki/Getting-started Clones the cppsharp-test repository and runs a basic test to verify the CppSharp build. Ensure the cppsharp-test directory is in the same location as the CppSharp directory, and that the CppSharp directory is named 'cppsharp'. ```shell git clone git://github.com/tomba/cppsharp-test.git cd cppsharp-test make runtest ``` -------------------------------- ### Generate VS Solution on Windows Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md Use this command to generate the Visual Studio solution files for CppSharp on Windows. Ensure you are in the \\build directory. ```shell cd \build build.sh generate -configuration Release -platform x64 ``` -------------------------------- ### Compile CppSharp on Windows Source: https://github.com/mono/cppsharp/wiki/Getting-started Generates Visual Studio projects and compiles CppSharp in Release configuration for x86 platform. Building in Release is recommended for performance. ```shell cd \build generateprojects.bat msbuild vs2013\CppSharp.sln /p:Configuration=Release;Platform=x86 ``` -------------------------------- ### ASTContext Extension Methods for Postprocessing Source: https://context7.com/mono/cppsharp/llms.txt Demonstrates various ASTContext extension methods for postprocessing C++ bindings. These methods allow fine-grained control over generated code, such as renaming, ignoring, and type conversions. ```csharp using CppSharp.AST; // Called inside ILibrary.Postprocess(Driver driver, ASTContext ctx): // Change a class to be generated as a .NET value type (struct) instead of reference type ctx.SetClassAsValueType("Vector3"); // Rename a free function in the output bindings ctx.SetNameOfFunction("glGenBuffers", "GenBuffers"); // Drop a specific field from a class's generated output ctx.IgnoreClassField("Foo", "internalHandle"); // Ignore a specific function entirely ctx.IgnoreFunctionWithName("SDL_Error"); // Ignore any enum that has an item with the given name ctx.IgnoreEnumWithMatchingItem("SDL_FALSE"); // Rename an enum found by one of its item names ctx.SetNameOfEnumWithMatchingItem("SDL_SCANCODE_UNKNOWN", "ScanCode"); // Rename an enum found by its own name ctx.SetNameOfEnumWithName("PIXELFORMAT", "PixelFormats"); // Rename a bound class ctx.SetClassBindName("assert_data", "AssertData"); // Generate a .NET enum from a set of C preprocessor #define macros ctx.GenerateEnumFromMacros("InitFlags", "SDL_INIT_(.*)").SetFlags(); ctx.GenerateEnumFromMacros("Endianness", "SDL_(.*)_ENDIAN"); // Mark a function parameter as out/in-out ctx.SetFunctionParameterUsage("SDL_PollEvent", 1, ParameterUsage.Out); // Ignore entire headers matching a wildcard pattern ctx.IgnoreHeadersWithName("SDL_atomic*"); ctx.IgnoreHeadersWithName("SDL_mutex*"); ``` -------------------------------- ### Manually clone LLVM repository Source: https://github.com/mono/cppsharp/blob/main/docs/LLVM.md Manually clone the LLVM source code if the build script's clone step fails. This is the first step in setting up the LLVM environment. ```bash git clone http://llvm.org/git/llvm.git ``` -------------------------------- ### Build Makefiles Manually on macOS/Linux Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md If the main build script fails on macOS/Linux, you can manually build the generated makefiles. This command is executed from the \\build directory. ```shell make -C gmake config=release_x64 ``` -------------------------------- ### Compile CppSharp on macOS/Linux Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md Compile the CppSharp project on macOS or Linux using the generated build files. This command should be executed from the \\build directory. ```shell ./build.sh -configuration Release -platform x64 ``` -------------------------------- ### Compile CppSharp on Windows Source: https://github.com/mono/cppsharp/blob/main/docs/GettingStarted.md Compile the CppSharp projects on Windows after generating the solution. This can be done via the command line or by opening and building the CppSharp.sln file in Visual Studio. ```shell build.sh -configuration Release -platform x64 ``` -------------------------------- ### Compile CppSharp on Mac OS X (64-bit) Source: https://github.com/mono/cppsharp/wiki/Getting-started Builds CppSharp using generated makefiles for a 64-bit release configuration on macOS. ```shell cd \build premake5-osx gmake config=release_x64 make ``` -------------------------------- ### Compile CppSharp on Mac OS X (32-bit) Source: https://github.com/mono/cppsharp/wiki/Getting-started Builds CppSharp using generated makefiles for a 32-bit release configuration on macOS. ```shell cd \build premake5-osx gmake config=release_x32 make ``` -------------------------------- ### Build CppSharp with Verbose Output Source: https://github.com/mono/cppsharp/wiki/Getting-started Compiles CppSharp with verbose output enabled, which can be helpful for debugging build issues. This command is an alternative to the standard make command. ```shell verbose=true make -C gmake config=release_x64 ``` -------------------------------- ### Implement Custom AST Transformation Pass Source: https://context7.com/mono/cppsharp/llms.txt Create custom AST transformations by implementing `TranslationUnitPass`. Override `Visit*` methods to intercept specific declaration types before code generation. ```csharp using CppSharp.AST; using CppSharp.Passes; // Custom pass: prepend "Native" prefix to all generated class names public class PrefixClassNamesPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (!base.VisitClassDecl(@class)) return false; if (@class.IsGenerated && !@class.Name.StartsWith("Native")) @class.Name = "Native" + @class.Name; return true; } public override bool VisitEnumDecl(Enumeration @enum) { if (!base.VisitEnumDecl(@enum)) return false; // Ignore anonymous enums leaking into global scope if (string.IsNullOrEmpty(@enum.Name)) @enum.ExplicitlyIgnore(); return true; } } // Register the custom pass in SetupPasses public void SetupPasses(Driver driver) { driver.Context.TranslationUnitPasses.AddPass(new PrefixClassNamesPass()); } ``` -------------------------------- ### Parse C/C++ Source File with ClangParser Source: https://context7.com/mono/cppsharp/llms.txt Invokes the Clang parser on a single source file. Configure language version, verbosity, include paths, and defines before parsing. Handles parsing errors and diagnostics. ```csharp using CppSharp; using CppSharp.Parser; var parserOptions = new ParserOptions { LanguageVersion = LanguageVersion.CPP20_GNU, Verbose = true // prints include directory resolution details }; // Populate system include paths and default compiler arguments for the host platform parserOptions.Setup(Platform.Host); parserOptions.AddIncludeDirs("/usr/local/include/mylib"); parserOptions.AddDefines("MY_DEFINE=1"); var file = "/path/to/MyHeader.h"; var parserResult = ClangParser.ParseSourceFile(file, parserOptions); if (parserResult.Kind != ParserResultKind.Success) { if (parserResult.Kind == ParserResultKind.FileNotFound) Console.Error.WriteLine($"{file} was not found."); for (uint i = 0; i < parserResult.DiagnosticsCount; i++) { var diag = parserResult.GetDiagnostics(i); Console.WriteLine("{0}({1},{2}): {3}: {4}", diag.FileName, diag.LineNumber, diag.ColumnNumber, diag.Level.ToString().ToLower(), diag.Message); } parserResult.Dispose(); return; } // Convert the native Clang AST to CppSharp's managed ASTContext var astContext = ClangParser.ConvertASTContext(parserOptions.ASTContext); parserResult.Dispose(); // Walk translation units foreach (var unit in astContext.TranslationUnits) { Console.WriteLine($"Translation unit: {unit.FileName}"); foreach (var decl in unit.Declarations) Console.WriteLine($" Declaration: {decl.Name} ({decl.GetType().Name})"); } // Output: // Translation unit: /path/to/MyHeader.h // Declaration: Foo (Class) // Declaration: FooAdd (Function) ``` -------------------------------- ### Manually clone Clang repository Source: https://github.com/mono/cppsharp/blob/main/docs/LLVM.md Manually clone the Clang source code into the LLVM tools directory. This is typically done after cloning the main LLVM repository. ```bash cd llvm/tools git clone http://llvm.org/git/clang.git ```