CppSharp Documentation

repository·main·Indexed 25 days ago

https://github.com/mono/cppsharp

CppSharp is a toolset and library that facilitates the use of native C/C++ code within the .NET ecosystem by generating managed API glue code. It uses the Clang C++ parser to consume header and library files, providing C# APIs that mirror Clang's AST and type system. It supports target languages including C# (P/Invoke) and C++/CLI, and handles complex C++ features such as virtual method overriding and multiple inheritance across multiple platforms (Windows, OS X, Linux) and runtimes (.NET, Mono).

Tokens
5.9K
Snippets
12
Records
41
Agent score
85%

What's inside CppSharp

  1. Overview of CppSharp

    main

    CppSharp is a toolset and library designed to facilitate the use of native C/C++ code within the .NET ecosystem. It consumes C/C++ header and library files to generate managed API glue code. This allows developers to either consume existing native libraries in managed code or add managed scripting support to a native codebase.

    Supported Target Languages:

    • C#
    • C++/CLI

    Core Capabilities:

    • AST: Provides C# APIs that mirror Clang's C/C++ AST and type system, including declarations, statements, expressions, types, object layouts, and visitors.
    • Parser: Uses the Clang C++ parser to parse C/C++ source code, library archives, and shared library symbols into a syntax tree.
    • Generator: Creates glue binding code from the syntax tree. It supports multiple backends (C++/CLI, C# P/Invoke), multiple ABIs (Itanium, MS, ARM, iOS), multiple platforms (Windows, OS X, Linux), and multiple runtimes (.NET, Mono). It handles complex C++ features like virtual method overriding, multiple inheritance (via C# interfaces), std::string, and default parameter values.
  2. Generate C++ bindings using ILibrary

    main

    To generate .NET bindings from C++ headers, implement the ILibrary interface and run the generation process using ConsoleDriver.Run.

    Implementing ILibrary requires defining four key methods:

    • Setup(Driver driver): Configure Clang parsing options and generator settings.
    • SetupPasses(Driver driver): Register transformation passes (e.g., renaming declarations or converting functions to instance methods).
    • Preprocess(Driver driver, ASTContext ctx): Perform transformations before passes are processed.
    • Postprocess(Driver driver, ASTContext ctx): Perform transformations after passes are processed.

    Example implementation:

    public interface ILibrary
    {
    	/// Setup the driver options here.
    	void Setup(Driver driver);
    
    	/// Setup your passes here.
    	void SetupPasses(Driver driver);
    
    	/// Do transformations that should happen before passes are processed.
    	void Preprocess(Driver driver, ASTContext ctx);
    
    	/// Do transformations that should happen after passes are processed.
    	void Postprocess(Driver driver, ASTContext ctx);
    }
    
    // To start the process:
    ConsoleDriver.Run(new SampleLibrary());
  3. Compile CppSharp on macOS or Linux

    main

    To build on macOS or Linux, use the build.sh script. Note that on Linux, only 64-bit builds are supported.

    1. Generate build files:

      cd <CppSharp>\build
      ./build.sh generate -configuration Release -platform x64

      Note: Use the -target-framework option to specify a valid .NET target framework.

    2. Compile:

      ./build.sh -configuration Release -platform x64

    Manual Build Fallback: If the script fails, you can build the components manually:

    • Makefiles: make -C gmake config=release_x64
    • VS Solution: msbuild CppSharp.sln -p:Configuration=Release -p:Platform=x64

    Verbose Output:

    • For make: make -C gmake config=release_x64 verbose=true
    • For msbuild: msbuild CppSharp.sln -p:Configuration=Release -p:Platform=x64 -verbosity:detailed
    cd <CppSharp>\build
    ./build.sh generate -configuration Release -platform x64
    ./build.sh -configuration Release -platform x64
  4. Compile CppSharp on Windows/Visual Studio

    main

    To build on Windows, use a Visual Studio developer command prompt. It is highly recommended to build in Release configuration to avoid slow Clang parser debug performance.

    1. Generate the VS solution:

      cd <CppSharp>\build
      build.sh generate -configuration Release -platform x64

      Note: Use the -target-framework option to specify a valid .NET target framework.

    2. Compile the projects: You can use the command line:

      build.sh -configuration Release -platform x64

      Or open CppSharp.sln in Visual Studio and press F5.

    Visual Studio Version Note: The solution is generated for Visual Studio 2019. If using a newer version, you may be prompted to retarget projects. Ensure you have the MSVC v142 - VS 2019 C++ x64/x86 build tools installed via the Visual Studio Installer.

    cd <CppSharp>\build
    build.sh generate -configuration Release -platform x64
    build.sh -configuration Release -platform x64
  5. Clone LLVM and Clang from Git manually

    main

    If the automated clone_llvm step fails, you can manually clone the repositories.

    Warning: You must use the specific revisions required by CppSharp to avoid compilation errors. Refer to the revisions specified in /build/llvm/LLVM-commit within the repository.

    Steps:

    1. Clone LLVM to <CppSharp>\build\llvm\llvm: git clone http://llvm.org/git/llvm.git
    2. Clone Clang to <CppSharp>\build\llvm\llvm\tools\clang: cd llvm/tools git clone http://llvm.org/git/clang.git
    3. Reset to the required revisions: git -C deps/llvm reset --hard <llvm-rev> git -C deps/llvm/tools/clang reset --hard <clang-rev>
    git clone http://llvm.org/git/llvm.git
    cd llvm/tools
    git clone http://llvm.org/git/clang.git
    
    # To apply required revisions:
    git -C deps/llvm reset --hard <llvm-rev>
    git -C deps/llvm/tools/clang reset --hard <clang-rev>
  6. Update Clang parser bindings in CppSharp

    main

    To update the Clang bindings used by CppSharp, follow these steps:

    1. Prepare Headers: Ensure you have the required headers package. Place the contents of the headers zip in <repo_root_dir>/build/headers/<target_triple> to allow binding generation for all platforms.
    2. Generate Patch: Run the CppSharp.Parser.Bootstrap project. This creates a source code patch in a folder named BootstrapPatch.
    3. Generate Bindings: Run CppSharp.Parser.Gen to generate the C# and C++/CLI bindings. This project builds and runs using the old bindings before overriding files with the bootstrap patch.

    Note: You may need to run this process twice if the new bindings cause new source code to be parsed (e.g., when adding support for new language features).

  7. Download pre-compiled LLVM and Clang packages

    main

    If you do not need to modify LLVM or Clang and simply want to build CppSharp, you should download the pre-compiled packages instead of compiling from source.

    Steps:

    1. Navigate to the <CppSharp>/build directory.
    2. Run the download script: ./build.sh download_llvm

    This will create one or more folders in <CppSharp>/build/llvm/ following the pattern llvm-<revision>-<os>-<configuration> containing the necessary headers and libraries.

    Troubleshooting: If the folders are not created (e.g., due to missing 7-Zip on Windows), you can manually extract the .7z archives into <CppSharp>/build/llvm.

  8. Pre-requisites for building CppSharp

    main

    CppSharp requires the following dependencies:

    • LLVM: A core dependency. The build.sh script will automatically download a compatible pre-built binary by default. Alternatively, you can build LLVM and Clang from source.
    • curl: Required by build scripts.
    • 7-Zip: Required on Windows.
    • Shell: Windows users require a sh environment (e.g., from Visual Studio or Git for Windows) to run the build scripts.
  9. Parse Doxygen-style C++ comments

    main

    CppSharp supports parsing Doxygen-style C++ comments and automatically translates them into .NET XML-style comments. It can also infer semantic parameter usage (such as ref or out) from Doxygen tags using the following passes:

    • CleanCommentsPass
    • FixParameterUsageFromComments
  10. Customize generation with Type Maps

    main
    If you need to customize what is generated for a specific type without modifying the entire structure, use the Type Maps feature. This allows you to hook into the generation process based on specific type patterns.