├── .clang-format ├── .editorconfig ├── .git-blame-ignore-revs ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE.md └── workflows │ ├── clang-format-check.yml │ ├── llvm-win.yml │ ├── llvm.yml │ └── main.yml ├── .gitignore ├── .gitmodules ├── CHANGELOG.md ├── CONTRIBUTING.md ├── CppSharp.code-workspace ├── CppSharp.sln.DotSettings ├── Directory.Build.props ├── Directory.Packages.props ├── LICENSE ├── README.md ├── RunClangFormat.sh ├── build ├── Helpers.lua ├── LLVM.lua ├── Tests.lua ├── build.sh ├── generate.sh ├── llvm │ ├── Directory.Build.props │ ├── LLVM-commit │ └── LLVM.lua ├── premake.sh ├── premake │ ├── premake.extensions.lua │ └── premake.fixes.lua ├── premake5.lua ├── scripts │ ├── Build.lua │ ├── Utils.lua │ └── readme.md └── test.sh ├── docs ├── DevManual.md ├── GeneratingBindings.md ├── GettingStarted.md ├── LLVM.md ├── UsersManual.md └── logo.svg ├── examples ├── Parser │ ├── Parser.cs │ └── premake5.lua └── SDL │ ├── Properties │ └── AssemblyInfo.cs │ ├── SDL.cs │ ├── SDL.lua │ └── premake5.lua ├── include ├── CppSharp.h └── FastDelegates.h ├── nuget.config ├── src ├── AST │ ├── ASTContext.cs │ ├── ASTVisitor.cs │ ├── Assembly.cs │ ├── Attribute.cs │ ├── Class.cs │ ├── ClassExtensions.cs │ ├── ClassLayout.cs │ ├── Comment.cs │ ├── Conversions.cs │ ├── CppSharp.AST.csproj │ ├── Declaration.cs │ ├── DeclarationsList.cs │ ├── Delegate.cs │ ├── Enumeration.cs │ ├── Event.cs │ ├── Expr.cs │ ├── Expression.cs │ ├── Field.cs │ ├── Friend.cs │ ├── Function.cs │ ├── FunctionExtensions.cs │ ├── IExpressionPrinter.cs │ ├── LayoutBase.cs │ ├── LayoutField.cs │ ├── Method.cs │ ├── Module.cs │ ├── Namespace.cs │ ├── Preprocessor.cs │ ├── Property.cs │ ├── PropertyExtensions.cs │ ├── Reference.cs │ ├── SourceLocation.cs │ ├── Statement.cs │ ├── Stmt.cs │ ├── StmtVisitor.cs │ ├── SymbolContext.cs │ ├── TargetTriple.cs │ ├── Template.cs │ ├── TranslationUnit.cs │ ├── Type.cs │ ├── TypeExtensions.cs │ ├── Typedef.cs │ ├── Variable.cs │ └── premake5.lua ├── CLI │ ├── CLI.cs │ ├── CppSharp.CLI.csproj │ ├── Generator.cs │ ├── LuaContext.cs │ ├── Options.cs │ └── premake5.lua ├── Core │ ├── Compilation.cs │ ├── CppSharp.csproj │ ├── Diagnostics.cs │ ├── Platform.cs │ ├── Toolchains │ │ ├── MSVCToolchain.cs │ │ ├── ManagedToolchain.cs │ │ └── XcodeToolchain.cs │ └── premake5.lua ├── CppParser │ ├── APValuePrinter.h │ ├── AST.cpp │ ├── AST.h │ ├── ASTNameMangler.cpp │ ├── ASTNameMangler.h │ ├── Bindings │ │ ├── CLI │ │ │ ├── AST.cpp │ │ │ ├── AST.h │ │ │ ├── CppParser.cpp │ │ │ ├── CppParser.h │ │ │ ├── Decl.cpp │ │ │ ├── Decl.h │ │ │ ├── Expr.cpp │ │ │ ├── Expr.h │ │ │ ├── Sources.cpp │ │ │ ├── Sources.h │ │ │ ├── Stmt.cpp │ │ │ ├── Stmt.h │ │ │ ├── Target.cpp │ │ │ ├── Target.h │ │ │ ├── Types.cpp │ │ │ ├── Types.h │ │ │ └── premake5.lua │ │ ├── CSharp │ │ │ ├── CppSharp.Parser.CSharp.csproj │ │ │ ├── i686-apple-darwin12.4.0 │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── CppSharp.CppParser.dll-templates.cpp │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ ├── i686-pc-win32-msvc-d │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ ├── i686-pc-win32-msvc │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── CppSharp.CppParser.dll-templates.cpp │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ ├── premake5.lua │ │ │ ├── x86_64-apple-darwin12.4.0 │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── CppSharp.CppParser.dll-templates.cpp │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ ├── x86_64-linux-gnu-cxx11abi │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ ├── x86_64-linux-gnu │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── CppSharp.CppParser.dll-templates.cpp │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ ├── x86_64-pc-win32-msvc-d │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── CppSharp.CppParser.dll-templates.cpp │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ │ └── x86_64-pc-win32-msvc │ │ │ │ ├── CppSharp.CppParser-symbols.cpp │ │ │ │ ├── CppSharp.CppParser.cs │ │ │ │ ├── CppSharp.CppParser.dll-templates.cpp │ │ │ │ ├── Std-symbols.cpp │ │ │ │ └── Std.cs │ │ └── premake5.lua │ ├── Bootstrap │ │ ├── Bootstrap.cs │ │ ├── CodeGeneratorHelpers.cs │ │ ├── CppSharp.Parser.Bootstrap.csproj │ │ ├── IgnoreMethodsWithParametersPass.cs │ │ ├── Properties │ │ │ └── launchSettings.json │ │ ├── StmtCodeGenerators.cs │ │ └── premake5.lua │ ├── CXXABI.h │ ├── Comments.cpp │ ├── CppParser.cpp │ ├── CppParser.h │ ├── Decl.h │ ├── ELFDumper.h │ ├── Expr.cpp │ ├── Expr.h │ ├── Helpers.h │ ├── Link.cpp │ ├── ParseExpr.cpp │ ├── ParseStmt.cpp │ ├── Parser.cpp │ ├── Parser.h │ ├── ParserGen │ │ ├── CppSharp.Parser.Gen.csproj │ │ ├── ParserGen.cs │ │ ├── Properties │ │ │ └── launchSettings.json │ │ └── premake5.lua │ ├── Sources.cpp │ ├── Sources.h │ ├── Stmt.cpp │ ├── Stmt.h │ ├── Target.cpp │ ├── Target.h │ ├── Types.h │ └── premake5.lua ├── Generator.Tests │ ├── AST │ │ └── TestAST.cs │ ├── ASTTestFixture.cs │ ├── CppSharp.Generator.Tests.csproj │ ├── GeneratorTest.cs │ ├── Passes │ │ └── TestPasses.cs │ ├── QueryHelpers.cs │ ├── ReadNativeDependenciesTest.cs │ ├── ReadNativeSymbolsTest.cs │ └── premake5.lua ├── Generator │ ├── AST │ │ ├── ASTRecord.cs │ │ ├── Utils.cs │ │ └── VTables.cs │ ├── BindingContext.cs │ ├── ClassOptions.cs │ ├── CppSharp.Generator.csproj │ ├── Driver.cs │ ├── Extensions │ │ ├── FunctionExtensions.cs │ │ ├── LayoutFieldExtensions.cs │ │ ├── ParserIntTypeExtensions.cs │ │ ├── PrimitiveTypeExtensions.cs │ │ └── TypeExtensions.cs │ ├── Generator.cs │ ├── GeneratorKind.cs │ ├── Generators │ │ ├── C │ │ │ ├── CCodeGenerator.cs │ │ │ ├── CGenerator.cs │ │ │ ├── CppDefaultValuePrinter.cs │ │ │ ├── CppGenerator.cs │ │ │ ├── CppHeaders.cs │ │ │ ├── CppMarshal.cs │ │ │ ├── CppSources.cs │ │ │ └── CppTypePrinter.cs │ │ ├── CLI │ │ │ ├── CLIGenerator.cs │ │ │ ├── CLIHeaders.cs │ │ │ ├── CLIMarshal.cs │ │ │ ├── CLISources.cs │ │ │ ├── CLITemplate.cs │ │ │ ├── CLITypePrinter.cs │ │ │ └── CLITypeReferences.cs │ │ ├── CSharp │ │ │ ├── CSharpCommentPrinter.cs │ │ │ ├── CSharpExpressionPrinter.cs │ │ │ ├── CSharpGenerator.cs │ │ │ ├── CSharpLibrarySymbolTable.cs │ │ │ ├── CSharpMarshal.cs │ │ │ ├── CSharpSources.cs │ │ │ ├── CSharpSourcesExtensions.cs │ │ │ └── CSharpTypePrinter.cs │ │ ├── CodeGenerator.cs │ │ ├── Emscripten │ │ │ ├── EmscriptenGenerator.cs │ │ │ ├── EmscriptenHeaders.cs │ │ │ ├── EmscriptenMarshal.cs │ │ │ ├── EmscriptenModule.cs │ │ │ ├── EmscriptenSources.cs │ │ │ └── EmscriptenTypePrinter.cs │ │ ├── ExtensionMethods.cs │ │ ├── ITypePrinter.cs │ │ ├── MSBuildGenerator.cs │ │ ├── Marshal.cs │ │ ├── NAPI │ │ │ ├── NAPIGenerator.cs │ │ │ ├── NAPIHeaders.cs │ │ │ ├── NAPIHelpers.cs │ │ │ ├── NAPIMarshal.cs │ │ │ ├── NAPIModule.cs │ │ │ ├── NAPISources.cs │ │ │ ├── NAPITypeCheckGen.cs │ │ │ ├── NAPITypeCheckPass.cs │ │ │ └── NAPITypePrinter.cs │ │ ├── QuickJS │ │ │ ├── QuickJSGenerator.cs │ │ │ ├── QuickJSHeaders.cs │ │ │ ├── QuickJSMarshal.cs │ │ │ ├── QuickJSModule.cs │ │ │ ├── QuickJSSources.cs │ │ │ ├── QuickJSTypeCheckGen.cs │ │ │ ├── QuickJSTypePrinter.cs │ │ │ └── Runtime │ │ │ │ ├── CppSharp_QuickJS.cpp │ │ │ │ ├── CppSharp_QuickJS.h │ │ │ │ ├── CppSharp_QuickJS_Signal.cpp │ │ │ │ ├── CppSharp_QuickJS_Signal.h │ │ │ │ └── premake5.lua │ │ ├── TS │ │ │ ├── TSGenerator.cs │ │ │ ├── TSSources.cs │ │ │ └── TSTypePrinter.cs │ │ └── TypePrinter.cs │ ├── Library.cs │ ├── Options.cs │ ├── Passes │ │ ├── CheckAbiParameters.cs │ │ ├── CheckAmbiguousFunctions.cs │ │ ├── CheckDuplicatedNamesPass.cs │ │ ├── CheckEnumsPass.cs │ │ ├── CheckIgnoredDecls.cs │ │ ├── CheckKeywordNamesPass.cs │ │ ├── CheckMacrosPass.cs │ │ ├── CheckOperatorsOverloads.cs │ │ ├── CheckStaticClassPass.cs │ │ ├── CheckVirtualOverrideReturnCovariance.cs │ │ ├── CleanCommentsPass.cs │ │ ├── CleanInvalidDeclNamesPass.cs │ │ ├── CleanUnitPass.cs │ │ ├── ConstructorToConversionOperatorPass.cs │ │ ├── DelegatesPass.cs │ │ ├── EqualiseAccessOfOverrideAndBasePass.cs │ │ ├── ExpressionHelper.cs │ │ ├── ExtractInterfacePass.cs │ │ ├── FastDelegateToDelegatesPass.cs │ │ ├── FieldToPropertyPass.cs │ │ ├── FindSymbolsPass.cs │ │ ├── FixDefaultParamValuesOfOverridesPass.cs │ │ ├── FixParameterUsageFromComments.cs │ │ ├── FlattenAnonymousTypesToFields.cs │ │ ├── FunctionToInstanceMethodPass.cs │ │ ├── FunctionToStaticMethodPass.cs │ │ ├── GenerateAbstractImplementationsPass.cs │ │ ├── GenerateSymbolsPass.cs │ │ ├── GetterSetterToPropertyPass.cs │ │ ├── HandleDefaultParamValuesPass.cs │ │ ├── HandleVariableInitializerPass.cs │ │ ├── IgnoreSystemDeclarationsPass.cs │ │ ├── MakeProtectedNestedTypesPublicPass.cs │ │ ├── MarkEventsWithUniqueIdPass.cs │ │ ├── MarkUsedClassInternalsPass.cs │ │ ├── MarshalPrimitivePointersAsRefTypePass.cs │ │ ├── MatchParamNamesWithInstantiatedFromPass.cs │ │ ├── MoveFunctionToClassPass.cs │ │ ├── MultipleInheritancePass.cs │ │ ├── ParamTypeToInterfacePass.cs │ │ ├── Pass.cs │ │ ├── PassBuilder.cs │ │ ├── RenamePass.cs │ │ ├── ResolveIncompleteDeclsPass.cs │ │ ├── SpecializationMethodsWithDependentPointersPass.cs │ │ ├── StripUnusedSystemTypesPass.cs │ │ ├── SymbolsCodeGenerator.cs │ │ ├── TrimSpecializationsPass.cs │ │ ├── ValidateOperatorsPass.cs │ │ └── verbs.txt │ ├── Types │ │ ├── DeclMap.cs │ │ ├── DeclMapDatabase.cs │ │ ├── Std │ │ │ ├── Stdlib.CLI.cs │ │ │ ├── Stdlib.CSharp.cs │ │ │ └── Stdlib.cs │ │ ├── TypeIgnoreChecker.cs │ │ ├── TypeMap.cs │ │ └── TypeMapDatabase.cs │ ├── Utils │ │ ├── BlockGenerator.cs │ │ ├── ExpressionEvaluator.cs │ │ ├── FSM │ │ │ ├── ConsoleWriter.cs │ │ │ ├── DFSM.cs │ │ │ ├── Minimize.cs │ │ │ ├── NDFSM.cs │ │ │ ├── Program.cs │ │ │ └── Transition.cs │ │ ├── HtmlEncoder.cs │ │ ├── IEnumerableExtensions.cs │ │ ├── Options.cs │ │ ├── OrderedSet.cs │ │ ├── ProcessHelper.cs │ │ ├── TextGenerator.cs │ │ └── Utils.cs │ └── premake5.lua ├── Package │ └── CppSharp.Package.csproj ├── Parser │ ├── ASTConverter.Expr.cs │ ├── ASTConverter.Stmt.cs │ ├── ASTConverter.cs │ ├── BuildConfig.cs │ ├── CppSharp.Parser.csproj │ ├── LinkerOptions.cs │ ├── Parser.cs │ ├── ParserOptions.cs │ └── premake5.lua └── Runtime │ ├── CppSharp.Runtime.csproj │ ├── MarshalUtil.cs │ ├── Pointer.cs │ ├── SafeUnmanagedMemoryHandle.cs │ ├── SymbolResolver.cs │ ├── UTF32Marshaller.cs │ ├── UTF8Marshaller.cs │ ├── VTables.cs │ └── premake5.lua ├── tests ├── Builtins.h ├── Classes.h ├── Classes2.h ├── Delegates.h ├── Enums.h ├── Overloads.h ├── dotnet │ ├── CLI │ │ ├── CLI.Gen.cs │ │ ├── CLI.Gen.csproj │ │ ├── CLI.Tests.CLI.csproj │ │ ├── CLI.Tests.cs │ │ ├── CLI.cpp │ │ ├── CLI.h │ │ ├── NestedEnumInClassTest │ │ │ ├── ClassWithNestedEnum.cpp │ │ │ ├── ClassWithNestedEnum.h │ │ │ ├── NestedEnumConsumer.cpp │ │ │ └── NestedEnumConsumer.h │ │ ├── Properties │ │ │ └── launchSettings.json │ │ ├── UseTemplateTypeFromIgnoredClassTemplate │ │ │ ├── Employee.cpp │ │ │ ├── Employee.h │ │ │ ├── EmployeeForwardDecl.h │ │ │ ├── EmployeeOrg.cpp │ │ │ ├── EmployeeOrg.h │ │ │ └── IgnoredClassTemplateForEmployee.h │ │ └── premake4.lua │ ├── CSharp │ │ ├── AnonTypes.h │ │ ├── AnotherUnit.cpp │ │ ├── AnotherUnit.h │ │ ├── CSharp.CSharp.csproj │ │ ├── CSharp.Gen.cs │ │ ├── CSharp.Gen.csproj │ │ ├── CSharp.Tests.CSharp.csproj │ │ ├── CSharp.Tests.cs │ │ ├── CSharp.cpp │ │ ├── CSharp.h │ │ ├── CSharpPartialMethods.cs │ │ ├── CSharpTemplates.cpp │ │ ├── CSharpTemplates.h │ │ ├── ExcludedUnit.hpp │ │ ├── Properties │ │ │ └── launchSettings.json │ │ └── premake4.lua │ ├── Common │ │ ├── AnotherUnit.cpp │ │ ├── AnotherUnit.h │ │ ├── Common.CSharp.csproj │ │ ├── Common.Gen.cs │ │ ├── Common.Gen.csproj │ │ ├── Common.Tests.CLI.csproj │ │ ├── Common.Tests.CSharp.csproj │ │ ├── Common.Tests.cs │ │ ├── Common.cpp │ │ ├── Common.h │ │ ├── Properties │ │ │ └── launchSettings.json │ │ ├── interface.h │ │ └── premake4.lua │ ├── Directory.Build.props │ ├── Empty │ │ ├── Empty.Gen.cs │ │ ├── Empty.Tests.cs │ │ ├── Empty.cpp │ │ ├── Empty.h │ │ └── premake4.lua │ ├── Encodings │ │ ├── Encodings.CSharp.csproj │ │ ├── Encodings.Gen.cs │ │ ├── Encodings.Gen.csproj │ │ ├── Encodings.Tests.CSharp.csproj │ │ ├── Encodings.Tests.cs │ │ ├── Encodings.cpp │ │ ├── Encodings.h │ │ ├── Properties │ │ │ └── launchSettings.json │ │ └── premake4.lua │ ├── NamespacesBase │ │ ├── NamespacesBase.cpp │ │ ├── NamespacesBase.h │ │ ├── premake4.lua │ │ └── test.cs │ ├── NamespacesDerived │ │ ├── Independent.h │ │ ├── NamespacesDerived.Gen.cs │ │ ├── NamespacesDerived.Gen.csproj │ │ ├── NamespacesDerived.Tests.CSharp.csproj │ │ ├── NamespacesDerived.Tests.cs │ │ ├── NamespacesDerived.cpp │ │ ├── NamespacesDerived.h │ │ ├── Properties │ │ │ └── launchSettings.json │ │ └── premake4.lua │ ├── Native │ │ ├── AST.h │ │ ├── ASTExtensions.h │ │ ├── Enums.h │ │ ├── Passes.h │ │ ├── Templates.h │ │ ├── linux │ │ │ └── libexpat.so.0 │ │ ├── macos │ │ │ └── libexpat.dylib │ │ └── windows │ │ │ └── libexpat.dll │ ├── StandardLib │ │ ├── Properties │ │ │ └── launchSettings.json │ │ ├── StandardLib.Gen.cs │ │ ├── StandardLib.Gen.csproj │ │ ├── StandardLib.Tests.CLI.csproj │ │ ├── StandardLib.Tests.cs │ │ ├── StandardLib.cpp │ │ ├── StandardLib.h │ │ └── premake4.lua │ ├── Test.Bindings.props │ ├── Test.Common.props │ ├── Test.Generator.props │ ├── Test.props │ ├── Tests.h │ └── VTables │ │ ├── Properties │ │ └── launchSettings.json │ │ ├── VTables.CSharp.csproj │ │ ├── VTables.Gen.cs │ │ ├── VTables.Gen.csproj │ │ ├── VTables.Tests.CSharp.csproj │ │ ├── VTables.Tests.cs │ │ ├── VTables.cpp │ │ ├── VTables.h │ │ └── premake4.lua ├── emscripten │ ├── .gitignore │ ├── bindings.lua │ ├── premake5.lua │ ├── test.mjs │ ├── test.sh │ └── utils.mjs ├── napi │ ├── .gitignore │ ├── premake5.lua │ ├── test.js │ └── test.sh ├── quickjs │ ├── .gitignore │ ├── bindings.lua │ ├── bootstrap.sh │ ├── premake5.lua │ ├── test-prop.js │ ├── test.js │ └── test.sh ├── test.sh └── ts │ ├── .gitignore │ ├── test.sh │ ├── test.ts │ └── tsconfig.json └── version.json /.git-blame-ignore-revs: -------------------------------------------------------------------------------- 1 | # When making commits that are strictly formatting/style changes, add the 2 | # commit hash here, so git blame can ignore the change. See docs for more 3 | # details: 4 | # https://git-scm.com/docs/git-config#Documentation/git-config.txt-blameignoreRevsFile 5 | # 6 | # 7 | # Example entries: 8 | # 9 | # # Formating changes 10 | # # rename something internal 11 | 4352a86efc9a0270ecd0c1712c9f470a9bd8fb75 # Format all c++ files -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Explicitly declare text files you want to always be normalized and converted 2 | # to native line endings on checkout. 3 | *.c text 4 | *.h text 5 | *.cpp text 6 | *.cs text diff=csharp 7 | *.lua text 8 | 9 | # Declare files that will always have CRLF line endings on checkout. 10 | *.sln text eol=crlf 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ##### Brief Description 2 | 3 | 4 | 5 | OS: Windows / OS X / Linux (include version and/or distro) 6 | 7 | 8 | ##### Used headers 9 | 10 | 11 | 12 | ##### Used settings 13 | 14 | 15 | Target: MSVC/GCC/Clang 16 | 17 | Other settings 18 | 19 | 20 | ##### Stack trace or incompilable generated code 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /.github/workflows/clang-format-check.yml: -------------------------------------------------------------------------------- 1 | name: clang-format Check 2 | 3 | 4 | on: [push, pull_request, workflow_dispatch] 5 | 6 | # Cancel any previous workflows if the pull request was updated 7 | concurrency: 8 | group: ${{ github.workflow }}-${{ github.ref || github.run_id }} 9 | cancel-in-progress: true 10 | 11 | jobs: 12 | formatting-check: 13 | name: Formatting Check 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | path: 18 | - 'src' 19 | - 'tests' 20 | 21 | steps: 22 | - uses: actions/checkout@v4 23 | 24 | - name: Run clang-format style check for C/C++/Protobuf programs. 25 | uses: jidicula/clang-format-action@v4.14.0 26 | with: 27 | clang-format-version: 19 28 | fallback-style: none 29 | check-path: ${{ matrix.path }} 30 | exclude-regex: '(Bindings|CLI)/|(CppParser/(Parse)?(Expr|Stmt))' 31 | -------------------------------------------------------------------------------- /.github/workflows/llvm-win.yml: -------------------------------------------------------------------------------- 1 | name: LLVM-win 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | build: 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | os: [windows-2022] 12 | platform: [x64] 13 | build-cfg: [Debug, DebugOpt, Release] 14 | 15 | runs-on: ${{ matrix.os }} 16 | 17 | env: 18 | VS_VERSION: "Program Files/Microsoft Visual Studio/2022" 19 | PLATFORM: ${{ matrix.platform }} 20 | BUILD_CONFIGURATION: ${{ matrix.build-cfg }} 21 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 22 | 23 | steps: 24 | - name: Check out 25 | uses: actions/checkout@v4 26 | 27 | - uses: lukka/get-cmake@latest 28 | 29 | - name: Environment 30 | shell: cmd 31 | run: | 32 | call "C:\%VS_VERSION%\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" %PLATFORM% 33 | :: Loop over all environment variables and make them global using set-env. 34 | :: See: https://stackoverflow.com/a/39184941 35 | setlocal 36 | for /f "delims== tokens=1,2" %%a in ('set') do ( 37 | echo ::set-env name=%%a::%%b 38 | ) 39 | endlocal 40 | 41 | - name: Clone LLVM 42 | shell: bash 43 | run: build/build.sh clone_llvm 44 | 45 | - name: Build LLVM 46 | shell: bash 47 | run: build/build.sh build_llvm -platform $PLATFORM -configuration $BUILD_CONFIGURATION 48 | 49 | - name: Package LLVM 50 | shell: bash 51 | run: build/build.sh package_llvm -platform $PLATFORM -configuration $BUILD_CONFIGURATION 52 | 53 | - name: 'Upload Artifact' 54 | uses: actions/upload-artifact@v4 55 | with: 56 | name: llvm-${{ matrix.os }}-${{ matrix.platform }}-${{ matrix.build-cfg }} 57 | path: build/llvm/llvm-*-*.* 58 | -------------------------------------------------------------------------------- /.github/workflows/llvm.yml: -------------------------------------------------------------------------------- 1 | name: LLVM 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | build: 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | os: [ubuntu-22.04, macos-13] 12 | platform: [x64, arm64] 13 | build-cfg: [Debug, DebugOpt, Release] 14 | 15 | runs-on: ${{ matrix.os }} 16 | 17 | env: 18 | CC: ${{ startsWith(matrix.os, 'ubuntu') && 'gcc-11' || 'clang' }} 19 | CXX: ${{ startsWith(matrix.os, 'ubuntu') && 'g++-11' || 'clang++' }} 20 | PLATFORM: ${{ matrix.platform }} 21 | BUILD_CONFIGURATION: ${{ matrix.build-cfg }} 22 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: lukka/get-cmake@latest 27 | 28 | - name: Install cross compilers 29 | if: startsWith(matrix.os, 'ubuntu') && startsWith(matrix.platform, 'arm64') 30 | run: sudo apt install -y g++-aarch64-linux-gnu gcc-aarch64-linux-gnu 31 | 32 | - name: Clone LLVM 33 | shell: bash 34 | run: build/build.sh clone_llvm 35 | 36 | - name: Build LLVM 37 | shell: bash 38 | run: build/build.sh build_llvm -platform $PLATFORM -configuration $BUILD_CONFIGURATION 39 | 40 | - name: Package LLVM 41 | shell: bash 42 | run: build/build.sh package_llvm -platform $PLATFORM -configuration $BUILD_CONFIGURATION 43 | 44 | - name: 'Upload Artifact' 45 | uses: actions/upload-artifact@v4 46 | with: 47 | name: llvm-${{ matrix.os }}-${{ matrix.platform }}-${{ matrix.build-cfg }} 48 | overwrite: true 49 | path: build/llvm/llvm-*-*.* 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pidb 2 | configure 3 | install-sh 4 | aclocal.m4 5 | config.status 6 | config.log 7 | autom4te.cache 8 | missing 9 | *Makefile 10 | *Makefile.in 11 | *.exe 12 | bin/ 13 | *.userprefs 14 | tests/output 15 | src/generator/generator 16 | src/BootstrapPatch 17 | *.pc 18 | .DS_Store 19 | *.user 20 | *.suo 21 | *.sdf 22 | *.opensdf 23 | *.pdb 24 | *.config 25 | !nuget.config 26 | *.vcxproj 27 | *.filters 28 | *.sln 29 | *.metagen 30 | *.ilk 31 | *.manifest 32 | *.tmp 33 | *.cache 34 | *.force 35 | *DesignTime* 36 | *TemporaryGeneratedFile* 37 | *FileListAbsolute* 38 | /build/llvm/llvm-* 39 | /build/llvm/*.tar.gz 40 | /build/scripts/.vagrant 41 | /build/*.zip 42 | /build/*.pkg 43 | /build/vs20* 44 | /build/gmake 45 | /build/headers 46 | /build/config.props 47 | /build/premake/premake5* 48 | /build/gen 49 | /artifacts 50 | /deps/llvm 51 | /external 52 | /extra 53 | /.idea/ 54 | /include/include 55 | /include/libc 56 | /include/libcxx 57 | /include/libunwind 58 | /include/linux 59 | /site 60 | /wip 61 | /.vs 62 | /.vscode 63 | 64 | # Nuget: do not include produced packages 65 | /build/nuget/*.nupkg 66 | /build/nuget/tools/* 67 | 68 | **/obj -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mono/CppSharp/e093f713b90d49528de13afd859e3d1f34cf3049/.gitmodules -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | The most common form of contribution to any open source project are bug reports. 2 | We always welcome them because we want to be aware of any shortcomings in our code in order to make the product better. 3 | However, as much as we would love to fix all reported issues in a timely manner, unfortunately we do not always have the resources to do so. 4 | Therefore we would like to ask you to help by either of: 5 | 6 | 1. Fixing the problem and sending us a pull request instead of working around issues with your own custom passes or in other ways. 7 | In most cases the former is no more difficult and takes just as much time. Besides, we are always here to help; 8 | 2. Using our support options at https://github.com/mono/CppSharp#support which guarantees a much faster resolution. -------------------------------------------------------------------------------- /CppSharp.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | CLI 3 | MSVC 4 | True 5 | True -------------------------------------------------------------------------------- /Directory.Packages.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 João Matos, Dimitar Dobrev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /build/generate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | DIR=$( cd "$( dirname "$0" )" && pwd ) 4 | "$DIR/build.sh" generate "$@" 5 | -------------------------------------------------------------------------------- /build/llvm/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /build/llvm/LLVM-commit: -------------------------------------------------------------------------------- 1 | 6eb36aed86ea276695697093eb8136554c29286b -------------------------------------------------------------------------------- /build/premake.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | DIR=$( cd "$( dirname "$0" )" && pwd ) 4 | 5 | case "$(uname -s)" in 6 | 7 | Darwin|Linux) 8 | "$DIR/premake/premake5" "$@" 9 | ;; 10 | 11 | CYGWIN*|MINGW32*|MSYS*|MINGW*) 12 | "$DIR/premake/premake5.exe" "$@" 13 | ;; 14 | 15 | *) 16 | echo "Unsupported platform" 17 | exit 1 18 | ;; 19 | esac 20 | -------------------------------------------------------------------------------- /build/premake/premake.extensions.lua: -------------------------------------------------------------------------------- 1 | premake.api.register { 2 | name = "workspacefiles", 3 | scope = "workspace", 4 | kind = "list:string", 5 | } 6 | 7 | -- https://github.com/premake/premake-core/issues/1061#issuecomment-441417853 8 | premake.override(premake.vstudio.sln2005, "projects", function(base, wks) 9 | if wks.workspacefiles and #wks.workspacefiles > 0 then 10 | premake.push('Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{' .. os.uuid("Solution Items:"..wks.name) .. '}"') 11 | premake.push("ProjectSection(SolutionItems) = preProject") 12 | for _, pattern in ipairs(wks.workspacefiles) do 13 | local matches = os.matchfiles(pattern) 14 | for _, file in ipairs(matches) do 15 | premake.w(file.." = "..file) 16 | end 17 | end 18 | premake.pop("EndProjectSection") 19 | premake.pop("EndProject") 20 | end 21 | base(wks) 22 | end) 23 | -------------------------------------------------------------------------------- /build/premake/premake.fixes.lua: -------------------------------------------------------------------------------- 1 | -- https://github.com/premake/premake-core/issues/1559 2 | premake.override(premake.vstudio.vc2010, "targetFramework", function(oldfn, prj) 3 | if prj.clr == "NetCore" then 4 | local action = premake.action.current() 5 | local tools = string.format(' ToolsVersion="%s"', action.vstudio.toolsVersion) 6 | local framework = prj.dotnetframework or action.vstudio.targetFramework or "4.0" 7 | 8 | premake.w('%s', framework) 9 | else 10 | oldfn(prj) 11 | end 12 | end) 13 | -------------------------------------------------------------------------------- /build/premake5.lua: -------------------------------------------------------------------------------- 1 | -- This is the starting point of the build scripts for the project. 2 | -- It defines the common build settings that all the projects share 3 | -- and calls the build scripts of all the sub-projects. 4 | 5 | config = {} 6 | 7 | include "Helpers.lua" 8 | 9 | WriteConfigForMSBuild() 10 | 11 | if _OPTIONS["config_only"] then 12 | return 13 | end 14 | 15 | include "LLVM.lua" 16 | 17 | workspace "CppSharp" 18 | configurations { _OPTIONS["configuration"] } 19 | platforms { target_architecture() } 20 | dotnetframework (targetframework) 21 | enabledefaultcompileitems "true" 22 | characterset "Unicode" 23 | symbols "On" 24 | 25 | location (actionbuilddir) 26 | objdir (prjobjdir) 27 | targetdir (bindircfg) 28 | debugdir (bindircfg) 29 | 30 | filter "action:vs*" 31 | location (rootdir) 32 | 33 | filter "system:windows" 34 | defines { "WINDOWS" } 35 | filter {} 36 | 37 | matches = os.matchfiles(path.join(rootdir, "*")) 38 | for _, file in ipairs(matches) do 39 | if not string.endswith(file, ".sln") then 40 | workspacefiles(file) 41 | end 42 | end 43 | 44 | workspacefiles(path.join(builddir, "premake5.lua")) 45 | workspacefiles(path.join(builddir, "*.sh")) 46 | workspacefiles(path.join(rootdir, ".github/workflows/*.yml")) 47 | workspacefiles(path.join(path.join(get_llvm_build_dir(), "/utils/"), "*.natvis")) 48 | workspacefiles(path.join(testsdir, "Test*.props")) 49 | 50 | group "Libraries" 51 | if EnableNativeProjects() then 52 | include (srcdir .. "/CppParser") 53 | end 54 | if EnabledManagedProjects() then 55 | include (srcdir .. "/Core") 56 | include (srcdir .. "/AST") 57 | include (srcdir .. "/CppParser/Bindings") 58 | include (srcdir .. "/CppParser/Bootstrap") 59 | include (srcdir .. "/CppParser/ParserGen") 60 | include (srcdir .. "/Parser") 61 | include (srcdir .. "/CLI") 62 | include (srcdir .. "/Generator") 63 | include (srcdir .. "/Generator.Tests") 64 | include (srcdir .. "/Runtime") 65 | end 66 | 67 | if not _OPTIONS["disable-tests"] then 68 | dofile "Tests.lua" 69 | 70 | group "Tests" 71 | IncludeTests() 72 | end 73 | 74 | if not _OPTIONS["disable-tests"] then 75 | if string.starts(action, "vs") then 76 | 77 | group "Examples" 78 | IncludeExamples() 79 | 80 | end 81 | end 82 | -------------------------------------------------------------------------------- /build/scripts/Build.lua: -------------------------------------------------------------------------------- 1 | require "Utils" 2 | 3 | function get_msbuild_path() 4 | local msbuild = '%SystemRoot%\\system32\\reg.exe query "HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0" /v MSBuildToolsPath' 5 | local val = execute(msbuild) 6 | 7 | for i in string.gmatch(val, "%S+") do 8 | if os.isdir(i) then 9 | return i 10 | end 11 | end 12 | 13 | error("MSBuild path could not be found in Windows registry.") 14 | end 15 | 16 | function msbuild(sln, conf, platform) 17 | local msbuild_path = "msbuild.exe" 18 | local sln = path.normalize(sln) 19 | 20 | local cmd = msbuild_path .. " " .. sln .. " /m" 21 | if conf ~= nil then 22 | cmd = cmd .. " /p:Configuration=" .. conf 23 | end 24 | 25 | if platform ~= nil then 26 | cmd = cmd .. " /p:Platform=" .. platform 27 | end 28 | 29 | execute_or_die(cmd) 30 | end 31 | 32 | function ninja(dir, action) 33 | local cmd = "ninja -C " .. dir 34 | if action then 35 | cmd = cmd .. " " .. action 36 | end 37 | return execute_or_die(cmd) 38 | end 39 | 40 | function run_premake(file, action) 41 | -- search for file with extension Lua 42 | if os.isfile(file .. ".lua") then 43 | file = file .. ".lua" 44 | end 45 | 46 | local cmd = string.format("%s --file=%s %s", _PREMAKE_COMMAND, file, action) 47 | return execute_or_die(cmd) 48 | end 49 | 50 | function build_cppsharp() 51 | -- install dependencies 52 | run_premake("Provision", "provision") 53 | 54 | -- if there is an llvm git clone then use it 55 | -- otherwise download and extract llvm/clang build 56 | 57 | run_premake("LLVM", "download_llvm") 58 | 59 | -- generate project files 60 | run_premake("../premake4", "gmake") 61 | 62 | -- build cppsharp 63 | --[[BUILD_CONF=release_x32; 64 | config=$BUILD_CONF make -C build/gmake/ 65 | BUILD_DIR=`ls build/gmake/lib` 66 | mkdir -p "$PWD"/build/gmake/lib/lib/"$BUILD_DIR" 67 | cp "$PWD"/build/gmake/lib/"$BUILD_DIR"/libNamespacesBase.* "$PWD"/build/gmake/lib/lib/"$BUILD_DIR" 68 | ]] 69 | end 70 | 71 | if _ACTION == "build_cppsharp" then 72 | build_cppsharp() 73 | os.exit() 74 | end 75 | 76 | 77 | -------------------------------------------------------------------------------- /build/scripts/readme.md: -------------------------------------------------------------------------------- 1 | This folder contains build and packaging scripts for CppSharp. 2 | -------------------------------------------------------------------------------- /build/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | DIR=$( cd "$( dirname "$0" )" && pwd ) 4 | "$DIR/build.sh" test "$@" 5 | -------------------------------------------------------------------------------- /docs/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | ++ 9 | 10 | -------------------------------------------------------------------------------- /examples/Parser/premake5.lua: -------------------------------------------------------------------------------- 1 | include "../../build/Tests.lua" 2 | 3 | project "Parser" 4 | kind "ConsoleApp" 5 | language "C#" 6 | debugdir "." 7 | links { "CppSharp.Parser" } 8 | 9 | SetupManagedProject() 10 | -------------------------------------------------------------------------------- /examples/SDL/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SDL")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SDL")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("5934cefb-a2b3-4556-901b-4d512f28aecc")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /examples/SDL/SDL.lua: -------------------------------------------------------------------------------- 1 | package.path = package.path .. "../build/?.lua;../../build/scripts/?.lua" 2 | require "Helpers" 3 | require "Utils" 4 | 5 | function clone_sdl() 6 | local sdl = path.getabsolute(examplesdir .. "/SDL/SDL-2.0") 7 | local repo = "https://github.com/spurious/SDL-mirror.git" 8 | 9 | if os.isdir(sdl) and not os.isdir(sdl .. "/.git") then 10 | error("SDL directory is not a git repository.") 11 | end 12 | 13 | if not os.isdir(sdl) then 14 | git.clone(sdl, repo) 15 | end 16 | end 17 | 18 | if _ACTION == "clone_sdl" then 19 | clone_sdl() 20 | os.exit() 21 | end 22 | -------------------------------------------------------------------------------- /examples/SDL/premake5.lua: -------------------------------------------------------------------------------- 1 | include "../../build/Tests.lua" 2 | 3 | project "SDL" 4 | SetupExampleProject() 5 | 6 | if config ~= nil and config.ExampleTests then 7 | 8 | project "SDL.Tests" 9 | 10 | kind "ConsoleApp" 11 | language "C#" 12 | location "." 13 | 14 | dependson "SDL" 15 | 16 | files 17 | { 18 | libdir .. "/SDL/SDL.cs", 19 | libdir .. "/SDL/SDL_assert.cs", 20 | libdir .. "/SDL/SDL_audio.cs", 21 | libdir .. "/SDL/SDL_blendmode.cs", 22 | libdir .. "/SDL/SDL_clipboard.cs", 23 | libdir .. "/SDL/SDL_cpuinfo.cs", 24 | libdir .. "/SDL/SDL_error.cs", 25 | libdir .. "/SDL/SDL_events.cs", 26 | libdir .. "/SDL/SDL_gamecontroller.cs", 27 | libdir .. "/SDL/SDL_gesture.cs", 28 | libdir .. "/SDL/SDL_hints.cs", 29 | libdir .. "/SDL/SDL_joystick.cs", 30 | libdir .. "/SDL/SDL_keyboard.cs", 31 | libdir .. "/SDL/SDL_keycode.cs", 32 | libdir .. "/SDL/SDL_loadso.cs", 33 | libdir .. "/SDL/SDL_log.cs", 34 | libdir .. "/SDL/SDL_messagebox.cs", 35 | libdir .. "/SDL/SDL_mouse.cs", 36 | libdir .. "/SDL/SDL_pixels.cs", 37 | libdir .. "/SDL/SDL_platform.cs", 38 | libdir .. "/SDL/SDL_power.cs", 39 | libdir .. "/SDL/SDL_rect.cs", 40 | libdir .. "/SDL/SDL_render.cs", 41 | libdir .. "/SDL/SDL_rwops.cs", 42 | libdir .. "/SDL/SDL_scancode.cs", 43 | libdir .. "/SDL/SDL_surface.cs", 44 | libdir .. "/SDL/SDL_thread.cs", 45 | libdir .. "/SDL/SDL_timer.cs", 46 | libdir .. "/SDL/SDL_touch.cs", 47 | libdir .. "/SDL/SDL_version.cs", 48 | libdir .. "/SDL/SDL_video.cs", 49 | "*.lua" 50 | } 51 | end 52 | -------------------------------------------------------------------------------- /nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/AST/Assembly.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("CppSharp.Generator")] 4 | -------------------------------------------------------------------------------- /src/AST/Attribute.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | /// 4 | /// Gives the ability to specify attributes to generate, for example ObsoleteAttribute. 5 | /// 6 | public class Attribute 7 | { 8 | public Attribute() 9 | { 10 | Type = typeof(object); 11 | Value = string.Empty; 12 | } 13 | 14 | public System.Type Type { get; set; } 15 | 16 | public string Value { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/AST/Conversions.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public enum MethodConversionKind 4 | { 5 | None, 6 | FunctionToInstanceMethod, 7 | FunctionToStaticMethod 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/AST/CppSharp.AST.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netstandard2.1 4 | true 5 | true 6 | 7 | -------------------------------------------------------------------------------- /src/AST/Delegate.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public class Delegate : Declaration 4 | { 5 | public FunctionType Type; 6 | 7 | public override T Visit(IDeclVisitor visitor) 8 | { 9 | return visitor.VisitDeclaration(this); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/AST/Event.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace CppSharp.AST 4 | { 5 | public class Event : DeclarationContext, ITypedDecl 6 | { 7 | public override T Visit(IDeclVisitor visitor) 8 | { 9 | return visitor.VisitEvent(this); 10 | } 11 | 12 | public Type Type => QualifiedType.Type; 13 | public QualifiedType QualifiedType { get; set; } 14 | 15 | public List Parameters { get; } = new List(); 16 | 17 | public Declaration OriginalDeclaration { get; set; } 18 | 19 | public int GlobalId { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/AST/Field.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | /// 4 | /// Represents a a C/C++ record field Decl. 5 | /// 6 | public class Field : Declaration, ITypedDecl 7 | { 8 | public Type Type { get { return QualifiedType.Type; } } 9 | public QualifiedType QualifiedType { get; set; } 10 | 11 | public Class Class { get; set; } 12 | 13 | public bool IsStatic { get; set; } 14 | 15 | public bool IsBitField { get; set; } 16 | 17 | public uint BitWidth { get; set; } 18 | 19 | 20 | public Field() 21 | { 22 | } 23 | 24 | public Field(string name, QualifiedType type, AccessSpecifier access) 25 | { 26 | Name = name; 27 | QualifiedType = type; 28 | Access = access; 29 | } 30 | 31 | public Field(Field field) : base(field) 32 | { 33 | QualifiedType = field.QualifiedType; 34 | Class = field.Class; 35 | IsBitField = field.IsBitField; 36 | BitWidth = field.BitWidth; 37 | } 38 | 39 | public override T Visit(IDeclVisitor visitor) 40 | { 41 | return visitor.VisitFieldDecl(this); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/AST/Friend.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public class Friend : Declaration 4 | { 5 | public Declaration Declaration { get; set; } 6 | 7 | public Friend() 8 | { 9 | } 10 | 11 | public Friend(Declaration declaration) 12 | { 13 | Declaration = declaration; 14 | } 15 | 16 | public override T Visit(IDeclVisitor visitor) 17 | { 18 | return visitor.VisitFriend(this); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/AST/IExpressionPrinter.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public interface IExpressionPrinter 4 | { 5 | string ToString(Type type); 6 | } 7 | 8 | public interface IExpressionPrinter : IExpressionPrinter, IExpressionVisitorObsolete 9 | { 10 | } 11 | } -------------------------------------------------------------------------------- /src/AST/LayoutBase.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public class LayoutBase 4 | { 5 | public uint Offset { get; set; } 6 | public Class Class { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/AST/LayoutField.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CppSharp.AST 4 | { 5 | public class LayoutField 6 | { 7 | public uint Offset { get; set; } 8 | public QualifiedType QualifiedType { get; set; } 9 | public string Name { get; set; } 10 | public IntPtr FieldPtr { get; set; } 11 | public bool IsVTablePtr { get { return FieldPtr == IntPtr.Zero; } } 12 | public ExpressionObsolete Expression { get; set; } 13 | 14 | public override string ToString() 15 | { 16 | return string.Format("{0} | {1}", Offset, Name); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/AST/Preprocessor.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public enum MacroLocation 4 | { 5 | Unknown, 6 | ClassHead, 7 | ClassBody, 8 | FunctionHead, 9 | FunctionParameters, 10 | FunctionBody, 11 | }; 12 | 13 | /// 14 | /// Base class that describes a preprocessed entity, which may 15 | /// be a preprocessor directive or macro expansion. 16 | /// 17 | public abstract class PreprocessedEntity 18 | { 19 | public MacroLocation MacroLocation = MacroLocation.Unknown; 20 | 21 | public abstract T Visit(IDeclVisitor visitor); 22 | } 23 | 24 | /// 25 | /// Represents a C preprocessor macro expansion. 26 | /// 27 | public class MacroExpansion : PreprocessedEntity 28 | { 29 | public string Name { get; set; } 30 | 31 | // Contains the macro expansion text. 32 | public string Text; 33 | 34 | public MacroDefinition Definition; 35 | 36 | public override T Visit(IDeclVisitor visitor) 37 | { 38 | //return visitor.VisitMacroExpansion(this); 39 | return default(T); 40 | } 41 | 42 | public override string ToString() 43 | { 44 | return Text; 45 | } 46 | } 47 | 48 | /// 49 | /// Represents a C preprocessor macro definition. 50 | /// 51 | public class MacroDefinition : PreprocessedEntity 52 | { 53 | // Contains the macro definition text. 54 | public string Expression; 55 | 56 | // Backing enumeration if one was generated. 57 | public Enumeration Enumeration; 58 | 59 | public string Name { get; set; } 60 | 61 | public override T Visit(IDeclVisitor visitor) 62 | { 63 | return visitor.VisitMacroDefinition(this); 64 | } 65 | 66 | public override string ToString() 67 | { 68 | return string.Format("{0} = {1}", Name, Expression); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/AST/PropertyExtensions.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST.Extensions; 2 | 3 | namespace CppSharp.AST 4 | { 5 | public static class PropertyExtensions 6 | { 7 | public static bool IsInRefTypeAndBackedByValueClassField(this Property p) 8 | { 9 | if (p.Field == null || ((Class)p.Namespace).IsRefType) 10 | return false; 11 | 12 | Type type; 13 | p.Field.Type.IsPointerTo(out type); 14 | type = type ?? p.Field.Type; 15 | 16 | Class decl; 17 | return type.TryGetClass(out decl) && decl.IsValueType; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/AST/Reference.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace CppSharp.AST 3 | { 4 | /// 5 | /// Represents a type reference. 6 | /// 7 | public class TypeReference 8 | { 9 | public Declaration Declaration; 10 | public string FowardReference; 11 | 12 | public override string ToString() 13 | { 14 | if (!string.IsNullOrWhiteSpace(FowardReference)) 15 | return FowardReference; 16 | 17 | return base.ToString(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/AST/Statement.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | public enum StatementClass 4 | { 5 | Any, 6 | BinaryOperator, 7 | DeclarationReference, 8 | Call, 9 | ConstructorReference, 10 | CXXOperatorCall, 11 | ImplicitCast, 12 | ExplicitCast, 13 | } 14 | 15 | public abstract class Statement 16 | { 17 | public StatementClass Class { get; set; } 18 | public Declaration Declaration { get; set; } 19 | public string String { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/AST/TargetTriple.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace CppSharp.AST 4 | { 5 | // over time we should turn this into a real class 6 | // like http://llvm.org/docs/doxygen/html/classllvm_1_1Triple.html 7 | public static class TargetTriple 8 | { 9 | public static bool IsWindows(this string targetTriple) 10 | { 11 | var parts = targetTriple.Split('-'); 12 | return parts.Contains("windows") || 13 | parts.Contains("win32") || parts.Contains("win64") || 14 | parts.Any(p => p.StartsWith("mingw")); 15 | } 16 | 17 | public static bool IsMacOS(this string targetTriple) 18 | { 19 | var parts = targetTriple.Split('-'); 20 | return parts.Contains("apple") || 21 | parts.Contains("darwin") || parts.Contains("osx"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/AST/Typedef.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.AST 2 | { 3 | /// 4 | /// Base class for declarations which introduce a typedef-name. 5 | /// 6 | public abstract class TypedefNameDecl : Declaration, ITypedDecl 7 | { 8 | public Type Type => QualifiedType.Type; 9 | public QualifiedType QualifiedType { get; set; } 10 | public bool IsSynthetized { get; set; } 11 | } 12 | 13 | /// 14 | /// Represents a type definition in C++. 15 | /// 16 | public class TypedefDecl : TypedefNameDecl 17 | { 18 | public override T Visit(IDeclVisitor visitor) 19 | { 20 | return visitor.VisitTypedefDecl(this); 21 | } 22 | } 23 | 24 | /// 25 | /// Represents a type alias in C++. 26 | /// 27 | public class TypeAlias : TypedefNameDecl 28 | { 29 | public TypeAliasTemplate DescribedAliasTemplate { get; set; } 30 | 31 | public override T Visit(IDeclVisitor visitor) 32 | { 33 | return visitor.VisitTypeAliasDecl(this); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/AST/Variable.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace CppSharp.AST 3 | { 4 | public class Variable : Declaration, ITypedDecl, IMangledDecl 5 | { 6 | public override T Visit(IDeclVisitor visitor) 7 | { 8 | return visitor.VisitVariableDecl(this); 9 | } 10 | 11 | public bool IsConstExpr { get; set; } 12 | public Type Type { get { return QualifiedType.Type; } } 13 | public QualifiedType QualifiedType { get; set; } 14 | public ExpressionObsolete Initializer { get; set; } 15 | 16 | public string Mangled { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/AST/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.AST") 2 | -------------------------------------------------------------------------------- /src/CLI/CppSharp.CLI.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | Exe 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/CLI/Options.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.Generators; 3 | using CppSharp.Passes; 4 | 5 | namespace CppSharp 6 | { 7 | enum TargetArchitecture 8 | { 9 | x86, 10 | x64, 11 | WASM32, 12 | WASM64 13 | } 14 | 15 | class Options 16 | { 17 | public List LuaBindingsFiles { get; } = new List(); 18 | 19 | public List HeaderFiles { get; } = new List(); 20 | 21 | public List IncludeDirs { get; } = new List(); 22 | 23 | public List LibraryDirs { get; } = new List(); 24 | 25 | public List Libraries { get; } = new List(); 26 | 27 | public List Arguments { get; } = new List(); 28 | 29 | public Dictionary Defines { get; } = new Dictionary(); 30 | 31 | public string OutputDir { get; set; } 32 | 33 | public string OutputNamespace { get; set; } 34 | 35 | public string OutputFileName { get; set; } 36 | 37 | public string InputLibraryName { get; set; } 38 | 39 | public string Prefix { get; set; } 40 | 41 | public TargetPlatform? Platform { get; set; } 42 | 43 | public TargetArchitecture Architecture { get; set; } = TargetArchitecture.x64; 44 | 45 | public GeneratorKind Kind { get; set; } = GeneratorKind.CSharp; 46 | 47 | public PropertyDetectionMode PropertyMode { get; set; } = PropertyDetectionMode.Keywords; 48 | 49 | public bool CheckSymbols { get; set; } 50 | 51 | public bool UnityBuild { get; set; } 52 | 53 | public bool Cpp11ABI { get; set; } 54 | 55 | public bool EnableExceptions { get; set; } 56 | 57 | public bool EnableRTTI { get; set; } 58 | 59 | public bool Compile { get; set; } 60 | 61 | public bool Debug { get; set; } 62 | 63 | public bool Verbose { get; set; } 64 | } 65 | } -------------------------------------------------------------------------------- /src/CLI/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.CLI") 2 | -------------------------------------------------------------------------------- /src/Core/Compilation.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp 2 | { 3 | public enum CompilationTarget 4 | { 5 | SharedLibrary, 6 | StaticLibrary, 7 | Application 8 | } 9 | 10 | public class CompilationOptions 11 | { 12 | /// 13 | /// Target platform for code compilation. 14 | /// 15 | public TargetPlatform? Platform; 16 | 17 | /// 18 | /// Specifies the VS version. 19 | /// 20 | /// When null, latest is used. 21 | public VisualStudioVersion VsVersion; 22 | 23 | // If code compilation is enabled, then sets the compilation target. 24 | public CompilationTarget Target; 25 | 26 | // If true, will compile the generated as a shared library / DLL. 27 | public bool CompileSharedLibrary => Target == CompilationTarget.SharedLibrary; 28 | 29 | // If true, will force the generation of debug metadata for the native 30 | // and managed code. 31 | public bool DebugMode; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Core/CppSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netstandard2.1 4 | true 5 | true 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/Core/Toolchains/ManagedToolchain.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using Microsoft.Win32; 6 | 7 | namespace CppSharp 8 | { 9 | public static class ManagedToolchain 10 | { 11 | public static string ReadMonoPathFromWindowsRegistry(bool prefer64bits = false) 12 | { 13 | using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 14 | prefer64bits ? RegistryView.Registry64 : RegistryView.Registry32)) 15 | { 16 | if (baseKey == null) 17 | return null; 18 | 19 | using (var subKey = baseKey.OpenSubKey(@"SOFTWARE\Mono")) 20 | { 21 | if (subKey == null) 22 | return null; 23 | 24 | return (string)subKey.GetValue("SdkInstallRoot", ""); 25 | } 26 | } 27 | } 28 | 29 | public static string FindMonoPath(bool prefer64bits = false) 30 | { 31 | if (Platform.IsWindows) 32 | { 33 | // Try to lookup the Mono SDK path from registry. 34 | string path = ReadMonoPathFromWindowsRegistry(prefer64bits); 35 | if (!string.IsNullOrEmpty(path)) 36 | return path; 37 | 38 | // If that fails, then lets try a default location. 39 | return @"C:\Program Files (x86)\Mono"; 40 | } 41 | else if (Platform.IsMacOS) 42 | return "/Library/Frameworks/Mono.framework/Versions/Current"; 43 | else 44 | return "/usr"; 45 | } 46 | 47 | public static string FindCSharpCompilerDir() 48 | { 49 | if (Platform.IsWindows) 50 | { 51 | List versions = MSVCToolchain.GetMSBuildSdks(); 52 | if (versions.Count == 0) 53 | throw new Exception("Could not find MSBuild SDK paths"); 54 | 55 | var sdk = versions.Last(); 56 | 57 | return sdk.Directory; 58 | } 59 | 60 | return FindMonoPath(); 61 | } 62 | 63 | public static string FindCSharpCompilerPath() 64 | { 65 | return Path.Combine(FindCSharpCompilerDir(), "bin", 66 | Platform.IsWindows ? "csc.exe" : "mcs"); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/Core/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp") 2 | -------------------------------------------------------------------------------- /src/CppParser/ASTNameMangler.h: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * 3 | * CppSharp 4 | * Licensed under the simplified BSD license. All rights reserved. 5 | * 6 | ************************************************************************/ 7 | 8 | #pragma once 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | 15 | namespace clang { 16 | class ASTContext; 17 | class MangleContext; 18 | struct ThunkInfo; 19 | } // namespace clang 20 | 21 | namespace llvm { 22 | class raw_ostream; 23 | } 24 | 25 | namespace CppSharp::CppParser { 26 | 27 | /// 28 | /// Helper class for getting the mangled name of a declaration 29 | /// 30 | /// Source adapted from https://clang.llvm.org/doxygen/Mangle_8cpp_source.html#l00394 31 | class ASTNameMangler 32 | { 33 | public: 34 | explicit ASTNameMangler(clang::ASTContext& Ctx); 35 | 36 | std::string GetName(const clang::Decl* D) const; 37 | bool WriteName(const clang::Decl* D, llvm::raw_ostream& OS) const; 38 | 39 | private: 40 | std::string GetMangledStructor(const clang::NamedDecl* ND, unsigned StructorType) const; 41 | std::string GetMangledThunk(const clang::CXXMethodDecl* MD, const clang::ThunkInfo& T, bool ElideOverrideInfo) const; 42 | bool WriteFuncOrVarName(const clang::NamedDecl* D, llvm::raw_ostream& OS) const; 43 | 44 | llvm::DataLayout DL; 45 | std::unique_ptr MC; 46 | }; 47 | 48 | } // namespace CppSharp::CppParser 49 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CLI/premake5.lua: -------------------------------------------------------------------------------- 1 | include "../../../../build/LLVM.lua" 2 | 3 | project "CppSharp.Parser.CLI" 4 | SetupNativeProject() 5 | 6 | kind "SharedLib" 7 | language "C++" 8 | 9 | dependson { "CppSharp.CppParser" } 10 | flags { common_flags } 11 | clr "NetCore" 12 | 13 | filter { "configurations:Debug*" } 14 | assemblydebug "On" 15 | 16 | filter "toolset:msc*" 17 | buildoptions { clang_msvc_flags } 18 | 19 | filter {} 20 | 21 | files 22 | { 23 | "**.h", 24 | "**.cpp", 25 | "**.lua" 26 | } 27 | 28 | includedirs 29 | { 30 | "../../../../include/", 31 | "../../../../src/CppParser/" 32 | } 33 | 34 | SetupLLVMIncludes() 35 | 36 | filter {} 37 | 38 | links { "CppSharp.CppParser" } 39 | 40 | CppSharpParserBindings = "CppSharp.Parser.CLI" -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/CppSharp.Parser.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | false 4 | false 5 | true 6 | true 7 | true 8 | 0109 9 | x86_64-pc-win32-msvc-d 10 | x86_64-pc-win32-msvc 11 | x86_64-linux-gnu-cxx11abi 12 | x86_64-linux-gnu 13 | x86_64-apple-darwin12.4.0 14 | i686-pc-win32-msvc 15 | i686-apple-darwin12.4.0 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/i686-apple-darwin12.4.0/CppSharp.CppParser.dll-templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template class vector; 6 | template class vector; 7 | template class vector; 8 | template class vector; 9 | template class vector; 10 | template class vector; 11 | template class vector; 12 | template class vector; 13 | template class vector; 14 | template class vector; 15 | template class vector; 16 | template class vector; 17 | template class vector; 18 | template class vector; 19 | template class vector; 20 | template class vector; 21 | template class vector; 22 | template class vector; 23 | template class vector; 24 | template class vector; 25 | template class vector; 26 | template class vector; 27 | template class vector; 28 | template class vector; 29 | template class vector; -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/i686-apple-darwin12.4.0/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template std::allocator::allocator() noexcept; 8 | template std::basic_string, std::allocator>::basic_string() noexcept(true); 9 | template std::basic_string, std::allocator>::~basic_string() noexcept; 10 | template std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char*); 11 | template const char* std::basic_string, std::allocator>::data() const noexcept; 12 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/i686-pc-win32-msvc-d/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template __declspec(dllexport) std::allocator::allocator() noexcept; 8 | template __declspec(dllexport) std::basic_string, std::allocator>::basic_string() noexcept(true); 9 | template __declspec(dllexport) std::basic_string, std::allocator>::~basic_string() noexcept; 10 | template __declspec(dllexport) std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char* const); 11 | template __declspec(dllexport) const char* std::basic_string, std::allocator>::data() const noexcept; 12 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/i686-pc-win32-msvc/CppSharp.CppParser.dll-templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template class vector; 6 | template class vector; 7 | template class vector; 8 | template class vector; 9 | template class vector; 10 | template class vector; 11 | template class vector; 12 | template class vector; 13 | template class vector; 14 | template class vector; 15 | template class vector; 16 | template class vector; 17 | template class vector; 18 | template class vector; 19 | template class vector; 20 | template class vector; 21 | template class vector; 22 | template class vector; 23 | template class vector; 24 | template class vector; 25 | template class vector; 26 | template class vector; 27 | template class vector; 28 | template class vector; 29 | template class vector; 30 | template class vector; -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/i686-pc-win32-msvc/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template __declspec(dllexport) std::allocator::allocator() noexcept; 8 | template __declspec(dllexport) std::basic_string, std::allocator>::basic_string() noexcept(true); 9 | template __declspec(dllexport) std::basic_string, std::allocator>::~basic_string() noexcept; 10 | template __declspec(dllexport) std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char* const); 11 | template __declspec(dllexport) const char* std::basic_string, std::allocator>::data() const noexcept; 12 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/premake5.lua: -------------------------------------------------------------------------------- 1 | if not EnabledManagedProjects() then 2 | return 3 | end 4 | 5 | SetupExternalManagedProject("CppSharp.Parser.CSharp") 6 | 7 | CppSharpParserBindings = "CppSharp.Parser.CSharp" 8 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-apple-darwin12.4.0/CppSharp.CppParser.dll-templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template class vector; 6 | template class vector; 7 | template class vector; 8 | template class vector; 9 | template class vector; 10 | template class vector; 11 | template class vector; 12 | template class vector; 13 | template class vector; 14 | template class vector; 15 | template class vector; 16 | template class vector; 17 | template class vector; 18 | template class vector; 19 | template class vector; 20 | template class vector; 21 | template class vector; 22 | template class vector; 23 | template class vector; 24 | template class vector; 25 | template class vector; 26 | template class vector; 27 | template class vector; 28 | template class vector; 29 | template class vector; -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-apple-darwin12.4.0/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template std::allocator::allocator() noexcept; 8 | template std::basic_string, std::allocator>::basic_string() noexcept(true); 9 | template std::basic_string, std::allocator>::~basic_string() noexcept; 10 | template std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char*); 11 | template const char* std::basic_string, std::allocator>::data() const noexcept; 12 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-linux-gnu-cxx11abi/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template std::allocator::allocator() noexcept; 8 | template std::allocator::~allocator() noexcept; 9 | template std::basic_string, std::allocator>::basic_string() noexcept(true); 10 | template std::basic_string, std::allocator>::~basic_string() noexcept; 11 | template std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char*); 12 | template const char* std::basic_string, std::allocator>::data() const noexcept; 13 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-linux-gnu/CppSharp.CppParser.dll-templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template class vector; 6 | template class vector; 7 | template class vector; 8 | template class vector; 9 | template class vector; 10 | template class vector; 11 | template class vector; 12 | template class vector; 13 | template class vector; 14 | template class vector; 15 | template class vector; 16 | template class vector; 17 | template class vector; 18 | template class vector; 19 | template class vector; 20 | template class vector; 21 | template class vector; 22 | template class vector; 23 | template class vector; 24 | template class vector; 25 | template class vector; 26 | template class vector; 27 | template class vector; 28 | template class vector; 29 | template class vector; -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-linux-gnu/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template std::allocator::allocator() noexcept; 8 | template std::allocator::~allocator() noexcept; 9 | template std::basic_string, std::allocator>::basic_string() noexcept; 10 | template std::basic_string, std::allocator>::~basic_string() noexcept; 11 | template std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char*); 12 | template const char* std::basic_string, std::allocator>::data() const noexcept; 13 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-pc-win32-msvc-d/CppSharp.CppParser.dll-templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template class vector; 6 | template class vector; 7 | template class vector; 8 | template class vector; 9 | template class vector; 10 | template class vector; 11 | template class vector; 12 | template class vector; 13 | template class vector; 14 | template class vector; 15 | template class vector; 16 | template class vector; 17 | template class vector; 18 | template class vector; 19 | template class vector; 20 | template class vector; 21 | template class vector; 22 | template class vector; 23 | template class vector; 24 | template class vector; 25 | template class vector; 26 | template class vector; 27 | template class vector; 28 | template class vector; 29 | template class vector; -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-pc-win32-msvc-d/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template __declspec(dllexport) std::allocator::allocator() noexcept; 8 | template __declspec(dllexport) std::basic_string, std::allocator>::basic_string() noexcept(true); 9 | template __declspec(dllexport) std::basic_string, std::allocator>::~basic_string() noexcept; 10 | template __declspec(dllexport) std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char* const); 11 | template __declspec(dllexport) const char* std::basic_string, std::allocator>::data() const noexcept; 12 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-pc-win32-msvc/CppSharp.CppParser.dll-templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template class vector; 6 | template class vector; 7 | template class vector; 8 | template class vector; 9 | template class vector; 10 | template class vector; 11 | template class vector; 12 | template class vector; 13 | template class vector; 14 | template class vector; 15 | template class vector; 16 | template class vector; 17 | template class vector; 18 | template class vector; 19 | template class vector; 20 | template class vector; 21 | template class vector; 22 | template class vector; 23 | template class vector; 24 | template class vector; 25 | template class vector; 26 | template class vector; 27 | template class vector; 28 | template class vector; 29 | template class vector; -------------------------------------------------------------------------------- /src/CppParser/Bindings/CSharp/x86_64-pc-win32-msvc/Std-symbols.cpp: -------------------------------------------------------------------------------- 1 | #define _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS 2 | #define _LIBCPP_HIDE_FROM_ABI 3 | 4 | #include 5 | #include 6 | 7 | template __declspec(dllexport) std::allocator::allocator() noexcept; 8 | template __declspec(dllexport) std::basic_string, std::allocator>::basic_string() noexcept(true); 9 | template __declspec(dllexport) std::basic_string, std::allocator>::~basic_string() noexcept; 10 | template __declspec(dllexport) std::basic_string, std::allocator>& std::basic_string, std::allocator>::assign(const char* const); 11 | template __declspec(dllexport) const char* std::basic_string, std::allocator>::data() const noexcept; 12 | -------------------------------------------------------------------------------- /src/CppParser/Bindings/premake5.lua: -------------------------------------------------------------------------------- 1 | include ("CSharp") 2 | 3 | if EnabledCLIProjects() and not os.getenv("CI") then 4 | 5 | include ("CLI") 6 | 7 | end -------------------------------------------------------------------------------- /src/CppParser/Bootstrap/CppSharp.Parser.Bootstrap.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | Exe 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/CppParser/Bootstrap/IgnoreMethodsWithParametersPass.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.AST.Extensions; 3 | using CppSharp.Passes; 4 | using System.Linq; 5 | 6 | namespace CppSharp 7 | { 8 | public class IgnoreMethodsWithParametersPass : TranslationUnitPass 9 | { 10 | public override bool VisitMethodDecl(Method method) 11 | { 12 | if (!base.VisitMethodDecl(method)) 13 | return false; 14 | 15 | if (!method.OriginalReturnType.Type.IsPrimitiveType(PrimitiveType.Void) && 16 | method.Parameters.Count( 17 | p => p.Kind == ParameterKind.Regular && p.DefaultValue == null) > 0) 18 | method.ExplicitlyIgnore(); 19 | 20 | return true; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/CppParser/Bootstrap/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "CppSharp.Parser.Bootstrap": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/CppParser/Bootstrap/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.Parser.Bootstrap") 2 | -------------------------------------------------------------------------------- /src/CppParser/CXXABI.h: -------------------------------------------------------------------------------- 1 | //===----- CXXABI.h - Interface to C++ ABIs ---------------------*- C++ -*-===// 2 | // 3 | // The LLVM Compiler Infrastructure 4 | // 5 | // This file is distributed under the University of Illinois Open Source 6 | // License. See LICENSE.TXT for details. 7 | // 8 | //===----------------------------------------------------------------------===// 9 | // 10 | // This provides an abstract class for C++ AST support. Concrete 11 | // subclasses of this implement AST support for specific C++ ABIs. 12 | // 13 | //===----------------------------------------------------------------------===// 14 | 15 | #ifndef LLVM_CLANG_AST_CXXABI_H 16 | #define LLVM_CLANG_AST_CXXABI_H 17 | 18 | namespace clang { 19 | 20 | class ASTContext; 21 | class MemberPointerType; 22 | 23 | /// Implements C++ ABI-specific semantic analysis functions. 24 | class CXXABI 25 | { 26 | public: 27 | virtual ~CXXABI(); 28 | 29 | /// Returns the size of a member pointer in multiples of the target 30 | /// pointer size. 31 | virtual unsigned getMemberPointerSize(const MemberPointerType* MPT) const = 0; 32 | 33 | /// Returns the default calling convention for C++ methods. 34 | virtual CallingConv getDefaultMethodCallConv() const = 0; 35 | 36 | // Returns whether the given class is nearly empty, with just virtual pointers 37 | // and no data except possibly virtual bases. 38 | virtual bool isNearlyEmpty(const CXXRecordDecl* RD) const = 0; 39 | }; 40 | 41 | /// Creates an instance of a C++ ABI class. 42 | CXXABI* CreateARMCXXABI(ASTContext& Ctx); 43 | CXXABI* CreateItaniumCXXABI(ASTContext& Ctx); 44 | CXXABI* CreateMicrosoftCXXABI(ASTContext& Ctx); 45 | } // namespace clang 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /src/CppParser/ParserGen/CppSharp.Parser.Gen.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | Exe 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/CppParser/ParserGen/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "CppSharp.Parser.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/CppParser/ParserGen/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.Parser.Gen") -------------------------------------------------------------------------------- /src/CppParser/Sources.cpp: -------------------------------------------------------------------------------- 1 | #include "Sources.h" 2 | 3 | namespace CppSharp { namespace CppParser { 4 | 5 | SourceLocation::SourceLocation() 6 | : ID(0) 7 | { 8 | } 9 | 10 | SourceLocation::SourceLocation(unsigned ID) 11 | : ID(ID) 12 | { 13 | } 14 | 15 | }} // namespace CppSharp::CppParser 16 | -------------------------------------------------------------------------------- /src/CppParser/Sources.h: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * 3 | * CppSharp 4 | * Licensed under the simplified BSD license. All rights reserved. 5 | * 6 | ************************************************************************/ 7 | 8 | #pragma once 9 | 10 | #include "Helpers.h" 11 | 12 | namespace CppSharp::CppParser { 13 | 14 | struct CS_API CS_VALUE_TYPE SourceLocation 15 | { 16 | SourceLocation(); 17 | SourceLocation(unsigned ID); 18 | unsigned ID; 19 | }; 20 | 21 | struct CS_API SourceRange 22 | { 23 | SourceLocation beginLoc; 24 | SourceLocation endLoc; 25 | }; 26 | 27 | } // namespace CppSharp::CppParser 28 | -------------------------------------------------------------------------------- /src/CppParser/Target.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * 3 | * CppSharp 4 | * Licensed under the simplified BSD license. All rights reserved. 5 | * 6 | ************************************************************************/ 7 | 8 | #include "Target.h" 9 | 10 | namespace CppSharp { namespace CppParser { 11 | 12 | ParserTargetInfo::ParserTargetInfo() 13 | : boolAlign(0) 14 | , boolWidth(0) 15 | , charAlign(0) 16 | , charWidth(0) 17 | , char16Align(0) 18 | , char16Width(0) 19 | , char32Align(0) 20 | , char32Width(0) 21 | , halfAlign(0) 22 | , halfWidth(0) 23 | , floatAlign(0) 24 | , floatWidth(0) 25 | , doubleAlign(0) 26 | , doubleWidth(0) 27 | , shortAlign(0) 28 | , shortWidth(0) 29 | , intAlign(0) 30 | , intWidth(0) 31 | , intMaxTWidth(0) 32 | , longAlign(0) 33 | , longWidth(0) 34 | , longDoubleAlign(0) 35 | , longDoubleWidth(0) 36 | , longLongAlign(0) 37 | , longLongWidth(0) 38 | , pointerAlign(0) 39 | , pointerWidth(0) 40 | , wCharAlign(0) 41 | , wCharWidth(0) 42 | , float128Align(0) 43 | , float128Width(0) 44 | { 45 | } 46 | 47 | ParserTargetInfo::~ParserTargetInfo() {} 48 | 49 | }} // namespace CppSharp::CppParser -------------------------------------------------------------------------------- /src/CppParser/Target.h: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * 3 | * CppSharp 4 | * Licensed under the simplified BSD license. All rights reserved. 5 | * 6 | ************************************************************************/ 7 | 8 | #pragma once 9 | 10 | #include "Helpers.h" 11 | 12 | namespace CppSharp { namespace CppParser { 13 | 14 | enum class ParserIntType 15 | { 16 | NoInt = 0, 17 | SignedChar, 18 | UnsignedChar, 19 | SignedShort, 20 | UnsignedShort, 21 | SignedInt, 22 | UnsignedInt, 23 | SignedLong, 24 | UnsignedLong, 25 | SignedLongLong, 26 | UnsignedLongLong 27 | }; 28 | 29 | struct CS_API ParserTargetInfo 30 | { 31 | ParserTargetInfo(); 32 | ~ParserTargetInfo(); 33 | std::string ABI; 34 | 35 | ParserIntType char16Type; 36 | ParserIntType char32Type; 37 | ParserIntType int64Type; 38 | ParserIntType intMaxType; 39 | ParserIntType intPtrType; 40 | ParserIntType sizeType; 41 | ParserIntType uIntMaxType; 42 | ParserIntType wCharType; 43 | ParserIntType wIntType; 44 | 45 | unsigned int boolAlign; 46 | unsigned int boolWidth; 47 | unsigned int charAlign; 48 | unsigned int charWidth; 49 | unsigned int char16Align; 50 | unsigned int char16Width; 51 | unsigned int char32Align; 52 | unsigned int char32Width; 53 | unsigned int halfAlign; 54 | unsigned int halfWidth; 55 | unsigned int floatAlign; 56 | unsigned int floatWidth; 57 | unsigned int doubleAlign; 58 | unsigned int doubleWidth; 59 | unsigned int shortAlign; 60 | unsigned int shortWidth; 61 | unsigned int intAlign; 62 | unsigned int intWidth; 63 | unsigned int intMaxTWidth; 64 | unsigned int longAlign; 65 | unsigned int longWidth; 66 | unsigned int longDoubleAlign; 67 | unsigned int longDoubleWidth; 68 | unsigned int longLongAlign; 69 | unsigned int longLongWidth; 70 | unsigned int pointerAlign; 71 | unsigned int pointerWidth; 72 | unsigned int wCharAlign; 73 | unsigned int wCharWidth; 74 | unsigned int float128Align; 75 | unsigned int float128Width; 76 | }; 77 | 78 | }} // namespace CppSharp::CppParser 79 | -------------------------------------------------------------------------------- /src/CppParser/premake5.lua: -------------------------------------------------------------------------------- 1 | clang_msvc_flags = 2 | { 3 | "/wd4146", "/wd4244", "/wd4800", "/wd4345", 4 | "/wd4355", "/wd4996", "/wd4624", "/wd4291", 5 | "/wd4251", 6 | "/wd4141", -- 'inline' : used more than once 7 | "/Zc:preprocessor" -- needed for newer Clang Options.inc (VA_ARGS) 8 | } 9 | 10 | if EnableNativeProjects() then 11 | 12 | project "CppSharp.CppParser" 13 | 14 | kind "SharedLib" 15 | language "C++" 16 | SetupNativeProject() 17 | rtti "Off" 18 | defines { "DLL_EXPORT" } 19 | 20 | if os.istarget("linux") then 21 | linkgroups "On" 22 | end 23 | 24 | filter "toolset:gcc*" 25 | buildoptions { "-Wno-nonnull" } 26 | 27 | filter "toolset:msc*" 28 | buildoptions { clang_msvc_flags } 29 | 30 | linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info 31 | 32 | filter {} 33 | 34 | files 35 | { 36 | "*.h", 37 | "*.cpp", 38 | "*.lua" 39 | } 40 | 41 | SearchLLVM() 42 | SetupLLVMIncludes() 43 | SetupLLVMLibs() 44 | CopyClangIncludes() 45 | 46 | filter {} 47 | 48 | project "Std-symbols" 49 | 50 | kind "SharedLib" 51 | language "C++" 52 | SetupNativeProject() 53 | rtti "Off" 54 | defines { "DLL_EXPORT" } 55 | 56 | filter { "toolset:msc*" } 57 | buildoptions { clang_msvc_flags } 58 | 59 | filter {} 60 | 61 | AddPlatformSpecificFiles("Bindings/CSharp", "Std-symbols.cpp") 62 | end 63 | -------------------------------------------------------------------------------- /src/Generator.Tests/CppSharp.Generator.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Generator.Tests/QueryHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using CppSharp.AST; 3 | 4 | namespace CppSharp.Generator.Tests 5 | { 6 | public static class LibraryQueryExtensions 7 | { 8 | public static Namespace Namespace(this TranslationUnit unit, string name) 9 | { 10 | return unit.FindNamespace(name); 11 | } 12 | 13 | public static Class Class(this ASTContext context, string name) 14 | { 15 | return context.FindClass(name).First(); 16 | } 17 | 18 | public static Function Function(this ASTContext context, string name) 19 | { 20 | return context.FindFunction(name).First(); 21 | } 22 | 23 | public static Enumeration Enum(this ASTContext context, string name) 24 | { 25 | return context.FindEnum(name).First(); 26 | } 27 | 28 | public static TypedefNameDecl Typedef(this ASTContext context, string name) 29 | { 30 | return context.FindTypedef(name).First(); 31 | } 32 | 33 | public static Field Field(this Class @class, string name) 34 | { 35 | return @class.Fields.Find(field => field.Name == name); 36 | } 37 | 38 | public static Method Method(this Class @class, string name) 39 | { 40 | return @class.Methods.Find(method => method.Name == name); 41 | } 42 | 43 | public static Parameter Param(this Function function, int index) 44 | { 45 | return function.Parameters[index]; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Generator.Tests/ReadNativeDependenciesTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.Utils; 3 | using NUnit.Framework; 4 | using CppSharp.AST; 5 | using System.IO; 6 | 7 | namespace CppSharp.Generator.Tests 8 | { 9 | [TestFixture] 10 | public class ReadNativeDependenciesTest 11 | { 12 | [Test] 13 | public void TestReadDependenciesWindows() 14 | { 15 | IList dependencies = GetDependencies("windows", "libexpat"); 16 | Assert.AreEqual("KERNEL32.dll", dependencies[0]); 17 | Assert.AreEqual("msvcrt.dll", dependencies[1]); 18 | Assert.AreEqual("USER32.dll", dependencies[2]); 19 | } 20 | 21 | [Test] 22 | public void TestReadDependenciesLinux() 23 | { 24 | IList dependencies = GetDependencies("linux", "libexpat"); 25 | Assert.AreEqual("libc.so.6", dependencies[0]); 26 | } 27 | 28 | [Test] 29 | public void TestReadDependenciesMacOS() 30 | { 31 | IList dependencies = GetDependencies("macos", "libexpat"); 32 | Assert.AreEqual("libexpat.1.dylib", dependencies[0]); 33 | Assert.AreEqual("libSystem.B.dylib", dependencies[1]); 34 | } 35 | 36 | private static IList GetDependencies(string dir, string library) 37 | { 38 | var driverOptions = new DriverOptions(); 39 | Module module = driverOptions.AddModule("Test"); 40 | module.LibraryDirs.Add(Path.Combine(GeneratorTest.GetTestsDirectory("Native"), dir)); 41 | module.Libraries.Add(library); 42 | using (var driver = new Driver(driverOptions)) 43 | { 44 | driver.Setup(); 45 | Assert.IsTrue(driver.ParseLibraries()); 46 | return driver.Context.Symbols.Libraries[0].Dependencies; 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /src/Generator.Tests/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.Generator.Tests") -------------------------------------------------------------------------------- /src/Generator/BindingContext.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Passes; 3 | using CppSharp.Types; 4 | using CppSharp.Parser; 5 | using System.Collections.Generic; 6 | 7 | namespace CppSharp.Generators 8 | { 9 | public class BindingContext 10 | { 11 | public DriverOptions Options { get; } 12 | public ParserOptions ParserOptions { get; set; } 13 | public LinkerOptions LinkerOptions { get; set; } 14 | 15 | public ASTContext ASTContext { get; set; } 16 | public ParserTargetInfo TargetInfo { get; set; } 17 | 18 | public SymbolContext Symbols { get; } 19 | 20 | public TypeMapDatabase TypeMaps { get; set; } 21 | public DeclMapDatabase DeclMaps { get; set; } 22 | 23 | public PassBuilder TranslationUnitPasses { get; } 24 | public PassBuilder GeneratorOutputPasses { get; } 25 | 26 | public BindingContext(DriverOptions options, ParserOptions parserOptions = null) 27 | { 28 | Options = options; 29 | ParserOptions = parserOptions; 30 | LinkerOptions = new LinkerOptions(); 31 | 32 | Symbols = new SymbolContext(); 33 | 34 | TranslationUnitPasses = new PassBuilder(this); 35 | GeneratorOutputPasses = new PassBuilder(this); 36 | } 37 | 38 | public void RunPasses() 39 | { 40 | Dictionary passesByType = new Dictionary(); 41 | int index = 0; 42 | TranslationUnitPasses.RunPasses(pass => 43 | { 44 | int count = passesByType.GetValueOrDefault(pass.GetType(), 0); 45 | Diagnostics.Debug("Pass '{0}'", pass); 46 | 47 | Diagnostics.PushIndent(); 48 | Options.TranslationUnitPassPreCallBack?.Invoke(pass, index, count); 49 | pass.Context = this; 50 | pass.VisitASTContext(ASTContext); 51 | Options.TranslationUnitPassPostCallBack?.Invoke(pass, index, count); 52 | Diagnostics.PopIndent(); 53 | passesByType[pass.GetType()] = count + 1; 54 | index += 1; 55 | }); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /src/Generator/ClassOptions.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp 2 | { 3 | public class ClassGenerationOptions 4 | { 5 | public bool GenerateNativeToManaged { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /src/Generator/CppSharp.Generator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | true 4 | true 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Generator/Extensions/FunctionExtensions.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | 3 | namespace CppSharp.Extensions 4 | { 5 | public static class FunctionExtensions 6 | { 7 | public static bool IsNativeMethod(this Function function) 8 | { 9 | var method = function as Method; 10 | if (method == null) 11 | return false; 12 | 13 | return method.Conversion == MethodConversionKind.None; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/Generator/Extensions/LayoutFieldExtensions.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.AST.Extensions; 3 | using CppSharp.Parser; 4 | 5 | namespace CppSharp.Extensions 6 | { 7 | public static class LayoutFieldExtensions 8 | { 9 | internal static int CalculateOffset(this LayoutField field, LayoutField previousField, ParserTargetInfo targetInfo) 10 | { 11 | var type = field.QualifiedType.Type.Desugar(); 12 | var prevFieldSize = previousField.QualifiedType.Type.Desugar().GetWidth(targetInfo) / 8; 13 | var unalignedOffset = previousField.Offset + prevFieldSize; 14 | var alignment = type.GetAlignment(targetInfo) / 8; 15 | 16 | if (type is ArrayType arrayType && arrayType.Type.Desugar().IsClass()) 17 | { 18 | // We have an array of structs. When we generate this field, we'll transform it into an fixed 19 | // array of bytes to which the elements in the embedded struct array can be bound (via their 20 | // accessors). At that point, the .Net subsystem will have no information in the generated 21 | // class on which to base its own alignment calculation. Consequently, we must generate 22 | // padding. Set alignment to indicate one-byte alignment which is consistent with the "fixed 23 | // byte fieldName[]" we'll eventually generate so that the offset we return here mimics what 24 | // will be the case once the struct[] -> byte[] transformation occurs. 25 | alignment = 1; 26 | } 27 | 28 | var alignedOffset = (unalignedOffset + (alignment - 1)) & -alignment; 29 | return (int)alignedOffset; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/Generator/Extensions/ParserIntTypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.Parser; 2 | 3 | namespace CppSharp.Extensions 4 | { 5 | public static class ParserIntTypeExtensions 6 | { 7 | public static bool IsSigned(this ParserIntType intType) 8 | { 9 | switch (intType) 10 | { 11 | case ParserIntType.SignedChar: 12 | case ParserIntType.SignedShort: 13 | case ParserIntType.SignedInt: 14 | case ParserIntType.SignedLong: 15 | case ParserIntType.SignedLongLong: 16 | return true; 17 | default: 18 | return false; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Generator/Extensions/TypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.AST.Extensions; 3 | using CppSharp.Parser; 4 | 5 | namespace CppSharp.Extensions 6 | { 7 | public static class TypeExtensions 8 | { 9 | public static int GetWidth(this Type type, ParserTargetInfo targetInfo) 10 | { 11 | if (type is TemplateSpecializationType specializationType) 12 | type = specializationType.Desugared.Type; 13 | 14 | if (type.IsPrimitiveType(out var primitiveType)) 15 | return (int)primitiveType.GetInfo(targetInfo, out _).Width; 16 | 17 | if (type.IsAddress()) 18 | return (int)targetInfo.PointerWidth; 19 | 20 | if (type.TryGetEnum(out Enumeration enumeration)) 21 | return GetWidth(enumeration.BuiltinType, targetInfo); 22 | 23 | if (type is ArrayType array) 24 | return (int)array.GetSizeInBits(); 25 | 26 | type.TryGetClass(out Class @class); 27 | return @class.Layout.Size * 8; 28 | } 29 | 30 | public static int GetAlignment(this Type type, ParserTargetInfo targetInfo) 31 | { 32 | if (type is TemplateSpecializationType specializationType) 33 | type = specializationType.Desugared.Type; 34 | 35 | if (type.IsPrimitiveType(out var primitiveType)) 36 | return (int)primitiveType.GetInfo(targetInfo, out _).Alignment; 37 | 38 | if (type.IsAddress()) 39 | return (int)targetInfo.PointerAlign; 40 | 41 | if (type.TryGetEnum(out Enumeration enumeration)) 42 | return GetAlignment(enumeration.BuiltinType, targetInfo); 43 | 44 | if (type is ArrayType array) 45 | return GetAlignment(array.Type.Desugar(), targetInfo); 46 | 47 | type.TryGetClass(out Class @class); 48 | if (@class.MaxFieldAlignment != 0) 49 | return @class.MaxFieldAlignment * 8; 50 | 51 | return @class.Layout.Alignment * 8; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Generator/Generators/C/CGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.Cpp; 4 | 5 | namespace CppSharp.Generators.C 6 | { 7 | /// 8 | /// C generator responsible for driving the generation of source and 9 | /// header files. 10 | /// 11 | public class CGenerator : Generator 12 | { 13 | public CGenerator(BindingContext context) : base(context) 14 | { 15 | } 16 | 17 | public override List Generate(IEnumerable units) 18 | { 19 | var outputs = new List(); 20 | 21 | var header = new CppHeaders(Context, units); 22 | outputs.Add(header); 23 | 24 | var source = new CppSources(Context, units); 25 | outputs.Add(source); 26 | 27 | return outputs; 28 | } 29 | 30 | public override bool SetupPasses() => true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Generator/Generators/C/CppDefaultValuePrinter.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using CppSharp.AST; 4 | 5 | namespace CppSharp.Generators.C 6 | { 7 | public class CppDefaultValuePrinter : CppTypePrinter 8 | { 9 | public CppDefaultValuePrinter(BindingContext context) : base(context) 10 | { 11 | } 12 | 13 | public override TypePrinterResult VisitBuiltinType(BuiltinType builtin, 14 | TypeQualifiers quals) 15 | { 16 | return VisitPrimitiveType(builtin.Type); 17 | } 18 | 19 | public override TypePrinterResult VisitPrimitiveType(PrimitiveType type) 20 | { 21 | switch (type) 22 | { 23 | case PrimitiveType.Bool: 24 | return PrintFlavorKind == CppTypePrintFlavorKind.Cpp ? "false" : "0"; 25 | case PrimitiveType.WideChar: 26 | case PrimitiveType.Char: 27 | case PrimitiveType.SChar: 28 | case PrimitiveType.UChar: 29 | case PrimitiveType.Char16: 30 | case PrimitiveType.Char32: 31 | case PrimitiveType.Short: 32 | case PrimitiveType.UShort: 33 | case PrimitiveType.Int: 34 | case PrimitiveType.UInt: 35 | case PrimitiveType.Long: 36 | case PrimitiveType.ULong: 37 | case PrimitiveType.LongLong: 38 | case PrimitiveType.ULongLong: 39 | case PrimitiveType.Int128: 40 | case PrimitiveType.UInt128: 41 | case PrimitiveType.Half: 42 | case PrimitiveType.Float: 43 | case PrimitiveType.Double: 44 | case PrimitiveType.LongDouble: 45 | case PrimitiveType.Float128: 46 | case PrimitiveType.Decimal: 47 | return "0"; 48 | case PrimitiveType.Null: 49 | case PrimitiveType.IntPtr: 50 | case PrimitiveType.UIntPtr: 51 | case PrimitiveType.String: 52 | return PrintFlavorKind == CppTypePrintFlavorKind.Cpp ? "nullptr" : "0"; 53 | default: 54 | throw new ArgumentOutOfRangeException(nameof(type), type, null); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Generator/Generators/C/CppGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.C; 4 | using CppSharp.Passes; 5 | 6 | namespace CppSharp.Generators.Cpp 7 | { 8 | /// 9 | /// C++ generator responsible for driving the generation of source and 10 | /// header files. 11 | /// 12 | public class CppGenerator : CGenerator 13 | { 14 | public CppGenerator(BindingContext context) : base(context) 15 | { 16 | } 17 | 18 | public override List Generate(IEnumerable units) 19 | { 20 | var outputs = new List(); 21 | 22 | var header = new CppHeaders(Context, units); 23 | outputs.Add(header); 24 | 25 | var source = new CppSources(Context, units); 26 | outputs.Add(source); 27 | 28 | return outputs; 29 | } 30 | 31 | public override bool SetupPasses() 32 | { 33 | new FixupPureMethodsPass().VisitASTContext(Context.ASTContext); 34 | return true; 35 | } 36 | 37 | public static bool ShouldGenerateClassNativeInstanceField(Class @class) 38 | { 39 | if (@class.IsStatic) 40 | return false; 41 | 42 | return @class.IsRefType && (!@class.HasBase || !@class.HasRefBase()); 43 | } 44 | } 45 | 46 | /// 47 | /// Removes the pureness of virtual abstract methods in C++ classes since 48 | /// the generated classes cannot have virtual pure methods, as they call 49 | /// the original pure method. 50 | /// This lets user code mark some methods as pure if needed, in that case 51 | /// the generator can generate the necessary pure C++ code annotations safely 52 | /// knowing the only pure functions were user-specified. 53 | /// 54 | public class FixupPureMethodsPass : TranslationUnitPass 55 | { 56 | public override bool VisitMethodDecl(Method method) 57 | { 58 | method.IsPure = false; 59 | return base.VisitMethodDecl(method); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Generator/Generators/CLI/CLIGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.C; 4 | 5 | namespace CppSharp.Generators.CLI 6 | { 7 | /// 8 | /// C++/CLI generator responsible for driving the generation of 9 | /// source and header files. 10 | /// 11 | public class CLIGenerator : Generator 12 | { 13 | public CLIGenerator(BindingContext context) : base(context) 14 | { 15 | } 16 | 17 | public override List Generate(IEnumerable units) 18 | { 19 | var outputs = new List(); 20 | 21 | var header = new CLIHeaders(Context, units); 22 | outputs.Add(header); 23 | 24 | var source = new CLISources(Context, units); 25 | outputs.Add(source); 26 | 27 | return outputs; 28 | } 29 | 30 | public override bool SetupPasses() => true; 31 | 32 | public static bool ShouldGenerateClassNativeField(Class @class) 33 | { 34 | if (@class.IsStatic) 35 | return false; 36 | 37 | return @class.IsRefType && (!@class.NeedsBase || !@class.HasRefBase()); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/Generator/Generators/CLI/CLITemplate.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.C; 4 | 5 | namespace CppSharp.Generators.CLI 6 | { 7 | /// 8 | /// There are two implementation 9 | /// for source (CLISources) and header (CLIHeaders) 10 | /// files. 11 | /// 12 | public abstract class CLITemplate : CCodeGenerator 13 | { 14 | protected CLITemplate(BindingContext context, IEnumerable units) 15 | : base(context, units) => typePrinter = new CLITypePrinter(context); 16 | 17 | public abstract override string FileExtension { get; } 18 | 19 | public abstract override void Process(); 20 | 21 | #region Helpers 22 | 23 | public string GetMethodName(Method method) 24 | { 25 | if (method.OperatorKind == CXXOperatorKind.Conversion || 26 | method.OperatorKind == CXXOperatorKind.ExplicitConversion) 27 | return "operator " + method.ConversionType; 28 | 29 | if (method.IsConstructor || method.IsDestructor) 30 | { 31 | var @class = (Class)method.Namespace; 32 | return @class.Name; 33 | } 34 | 35 | return method.Name; 36 | } 37 | 38 | public void GenerateMethodParameters(Method method) 39 | { 40 | for (var i = 0; i < method.Parameters.Count; ++i) 41 | { 42 | if (method.Conversion == MethodConversionKind.FunctionToInstanceMethod 43 | && i == 0) 44 | continue; 45 | 46 | var param = method.Parameters[i]; 47 | Write("{0}", CTypePrinter.VisitParameter(param)); 48 | if (i < method.Parameters.Count - 1) 49 | Write(", "); 50 | } 51 | } 52 | 53 | public string GenerateParametersList(List parameters) 54 | { 55 | var types = new List(); 56 | foreach (var param in parameters) 57 | types.Add(CTypePrinter.VisitParameter(param).ToString()); 58 | return string.Join(", ", types); 59 | } 60 | 61 | #endregion 62 | } 63 | } -------------------------------------------------------------------------------- /src/Generator/Generators/CSharp/CSharpGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Passes; 4 | using CppSharp.Parser; 5 | 6 | namespace CppSharp.Generators.CSharp 7 | { 8 | public class CSharpGenerator : Generator 9 | { 10 | public CSharpGenerator(BindingContext context) : base(context) 11 | { 12 | } 13 | 14 | public override List Generate(IEnumerable units) 15 | { 16 | var outputs = new List(); 17 | 18 | var gen = new CSharpSources(Context, units) { TypePrinter = (CSharpTypePrinter)typePrinter }; 19 | outputs.Add(gen); 20 | 21 | return outputs; 22 | } 23 | 24 | public override bool SetupPasses() 25 | { 26 | if (Context.Options.GenerateDefaultValuesForArguments) 27 | { 28 | Context.TranslationUnitPasses.AddPass(new FixDefaultParamValuesOfOverridesPass()); 29 | Context.TranslationUnitPasses.AddPass(new HandleDefaultParamValuesPass()); 30 | } 31 | 32 | // Both the CheckOperatorsOverloadsPass and CheckAbiParameters can 33 | // create and and new parameters to functions and methods. Make sure 34 | // CheckAbiParameters runs last because hidden structure parameters 35 | // should always occur first. 36 | 37 | if (Context.ParserOptions.LanguageVersion > LanguageVersion.C99_GNU) 38 | Context.TranslationUnitPasses.AddPass(new CheckAbiParameters()); 39 | 40 | return true; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Generator/Generators/Emscripten/EmscriptenHeaders.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | 4 | namespace CppSharp.Generators.Emscripten 5 | { 6 | /// 7 | /// Generates Emscripten Embind C/C++ header files. 8 | /// Embind documentation: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html 9 | /// 10 | public sealed class EmscriptenHeaders : EmscriptenCodeGenerator 11 | { 12 | public EmscriptenHeaders(BindingContext context, IEnumerable units) 13 | : base(context, units) 14 | { 15 | CTypePrinter.PushContext(TypePrinterContextKind.Managed); 16 | } 17 | 18 | //public override bool ShouldGenerateNamespaces => false; 19 | 20 | public override void Process() 21 | { 22 | GenerateFilePreamble(CommentKind.BCPL); 23 | 24 | PushBlock(BlockKind.Includes); 25 | WriteLine("#pragma once"); 26 | NewLine(); 27 | PopBlock(); 28 | 29 | var name = GetTranslationUnitName(TranslationUnit); 30 | WriteLine($"extern \"C\" void embind_init_{name}();"); 31 | } 32 | 33 | public override bool VisitClassDecl(Class @class) 34 | { 35 | return true; 36 | } 37 | 38 | public override bool VisitEvent(Event @event) 39 | { 40 | return true; 41 | } 42 | 43 | public override bool VisitFieldDecl(Field field) 44 | { 45 | return true; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Generator/Generators/Emscripten/EmscriptenMarshal.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.Generators.C; 2 | 3 | namespace CppSharp.Generators.Emscripten 4 | { 5 | public class EmscriptenMarshalNativeToManagedPrinter : MarshalPrinter 6 | { 7 | public EmscriptenMarshalNativeToManagedPrinter(MarshalContext marshalContext) 8 | : base(marshalContext) 9 | { 10 | } 11 | } 12 | 13 | public class EmscriptenMarshalManagedToNativePrinter : MarshalPrinter 14 | { 15 | public EmscriptenMarshalManagedToNativePrinter(MarshalContext ctx) 16 | : base(ctx) 17 | { 18 | Context.MarshalToNative = this; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Generator/Generators/Emscripten/EmscriptenTypePrinter.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.Generators.C; 2 | 3 | namespace CppSharp.Generators.Emscripten 4 | { 5 | public class EmscriptenTypePrinter : CppTypePrinter 6 | { 7 | public EmscriptenTypePrinter(BindingContext context) : base(context) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Generator/Generators/MSBuildGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using CppSharp.AST; 6 | 7 | namespace CppSharp.Generators 8 | { 9 | public class MSBuildGenerator : CodeGenerator 10 | { 11 | public MSBuildGenerator(BindingContext context, Module module, 12 | Dictionary libraryMappings) 13 | : base(context) 14 | { 15 | this.module = module; 16 | this.libraryMappings = libraryMappings; 17 | } 18 | 19 | public override string FileExtension => "csproj"; 20 | 21 | public override void Process() 22 | { 23 | var location = System.Reflection.Assembly.GetExecutingAssembly().Location; 24 | Write($@" 25 | 26 | 27 | netstandard2.1 28 | {(Context.TargetInfo.PointerWidth == 64 ? "x64" : "x86")} 29 | {Options.OutputDir} 30 | {module.LibraryName}.xml 31 | Release 32 | true 33 | false 34 | false 35 | false 36 | 37 | 38 | {string.Join(Environment.NewLine, module.CodeFiles.Select(c => 39 | $""))} 40 | 41 | 42 | {string.Join(Environment.NewLine, 43 | new[] { Path.Combine(Path.GetDirectoryName(location), "CppSharp.Runtime.dll") } 44 | .Union(module.Dependencies.Where(libraryMappings.ContainsKey).Select(d => libraryMappings[d])) 45 | .Select(reference => 46 | $@" 47 | {reference} 48 | "))} 49 | 50 | ".Trim()); 51 | } 52 | 53 | private readonly Module module; 54 | private readonly Dictionary libraryMappings; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Generator/Generators/Marshal.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Generators.C; 3 | using System; 4 | 5 | namespace CppSharp.Generators 6 | { 7 | public class MarshalContext : TypePrinter 8 | { 9 | public MarshalContext(BindingContext context, uint indentation) : base(context) 10 | { 11 | Before = new TextGenerator { CurrentIndentation = indentation }; 12 | Return = new TextGenerator { CurrentIndentation = indentation }; 13 | Cleanup = new TextGenerator { CurrentIndentation = indentation }; 14 | VarPrefix = new TextGenerator(); 15 | ArgumentPrefix = new TextGenerator(); 16 | Indentation = indentation; 17 | } 18 | 19 | public MarshalPrinter MarshalToNative; 20 | 21 | public TextGenerator Before { get; } 22 | public TextGenerator Return { get; } 23 | public TextGenerator Cleanup { get; } 24 | public TextGenerator VarPrefix { get; } 25 | public TextGenerator ArgumentPrefix { get; } 26 | 27 | public string ReturnVarName { get; set; } 28 | public QualifiedType ReturnType { get; set; } 29 | 30 | public string ArgName { get; set; } 31 | public int ParameterIndex { get; set; } 32 | public Function Function { get; set; } 33 | 34 | public uint Indentation { get; } 35 | } 36 | 37 | public abstract class MarshalPrinter : AstVisitor where C : MarshalContext where P : TypePrinter 38 | { 39 | public C Context { get; } 40 | 41 | protected MarshalPrinter(C ctx) 42 | { 43 | Context = ctx; 44 | typePrinter = (P)Activator.CreateInstance(typeof(P), ctx.Context); 45 | } 46 | 47 | protected P typePrinter; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Generator/Generators/NAPI/NAPIHeaders.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using CppSharp.AST; 4 | 5 | namespace CppSharp.Generators.Cpp 6 | { 7 | /// 8 | /// Generates Node N-API C/C++ header files. 9 | /// N-API documentation: https://nodejs.org/api/n-api.html 10 | /// 11 | public class NAPIHeaders : CppHeaders 12 | { 13 | public NAPIHeaders(BindingContext context, IEnumerable units) 14 | : base(context, units) 15 | { 16 | CTypePrinter.PushContext(TypePrinterContextKind.Managed); 17 | } 18 | 19 | public override void Process() 20 | { 21 | return; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Generator/Generators/NAPI/NAPIModule.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.C; 4 | 5 | namespace CppSharp.Generators.Cpp 6 | { 7 | /// 8 | /// Generates Node N-API C/C++ module init files. 9 | /// N-API documentation: https://nodejs.org/api/n-api.html 10 | /// 11 | public class NAPIModule : CCodeGenerator 12 | { 13 | public NAPIModule(BindingContext context, Module module) 14 | : base(context, module.Units.GetGenerated()) 15 | { 16 | CTypePrinter.PushContext(TypePrinterContextKind.Managed); 17 | } 18 | 19 | public override string FileExtension { get; } = "cpp"; 20 | 21 | public override void Process() 22 | { 23 | WriteInclude("node/node_api.h", CInclude.IncludeKind.Angled); 24 | WriteInclude("NAPIHelpers.h", CInclude.IncludeKind.Quoted); 25 | NewLine(); 26 | 27 | PushBlock(); 28 | foreach (var unit in TranslationUnits) 29 | { 30 | var name = NAPISources.GetTranslationUnitName(unit); 31 | WriteLine($"extern void register_{name}(napi_env env, napi_value exports);"); 32 | } 33 | PopBlock(NewLineKind.BeforeNextBlock); 34 | 35 | PushBlock(); 36 | WriteLine("// napi_value NAPI_MODULE_INITIALIZER(napi_env env, napi_value exports)"); 37 | WriteLine("NAPI_MODULE_INIT()"); 38 | WriteOpenBraceAndIndent(); 39 | 40 | foreach (var unit in TranslationUnits) 41 | { 42 | var name = NAPISources.GetTranslationUnitName(unit); 43 | WriteLine($"register_{name}(env, exports);"); 44 | } 45 | NewLine(); 46 | 47 | WriteLine("return nullptr;"); 48 | 49 | UnindentAndWriteCloseBrace(); 50 | PopBlock(NewLineKind.BeforeNextBlock); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /src/Generator/Generators/NAPI/NAPITypePrinter.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.Generators.C; 2 | 3 | namespace CppSharp.Generators.C 4 | { 5 | public class NAPITypePrinter : CppTypePrinter 6 | { 7 | public NAPITypePrinter(BindingContext context) : base(context) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Generator/Generators/QuickJS/QuickJSHeaders.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.C; 4 | 5 | namespace CppSharp.Generators.Cpp 6 | { 7 | /// 8 | /// Generates QuickJS C/C++ header files. 9 | /// QuickJS documentation: https://bellard.org/quickjs/ 10 | /// 11 | public class QuickJSHeaders : CppHeaders 12 | { 13 | public QuickJSHeaders(BindingContext context, IEnumerable units) 14 | : base(context, units) 15 | { 16 | CTypePrinter.PushContext(TypePrinterContextKind.Managed); 17 | } 18 | 19 | public override bool ShouldGenerateNamespaces => false; 20 | 21 | public override void Process() 22 | { 23 | GenerateFilePreamble(CommentKind.BCPL); 24 | 25 | PushBlock(BlockKind.Includes); 26 | WriteLine("#pragma once"); 27 | NewLine(); 28 | 29 | var include = new CInclude() 30 | { 31 | File = "quickjs.h", 32 | Kind = CInclude.IncludeKind.Angled 33 | }; 34 | 35 | WriteInclude(include); 36 | NewLine(); 37 | PopBlock(); 38 | 39 | VisitNamespace(TranslationUnit); 40 | } 41 | 42 | public override bool VisitFunctionDecl(Function function) 43 | { 44 | Write("extern \"C\" "); 45 | WriteLine($"JSValue js_{function.Name}(JSContext* ctx, JSValueConst this_val,"); 46 | WriteLineIndent("int argc, JSValueConst* argv);"); 47 | 48 | return true; 49 | } 50 | 51 | public override bool VisitEvent(Event @event) 52 | { 53 | return true; 54 | } 55 | 56 | public override bool VisitFieldDecl(Field field) 57 | { 58 | return true; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/Generator/Generators/QuickJS/QuickJSTypePrinter.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.Generators.C 2 | { 3 | public class QuickJSTypePrinter : CppTypePrinter 4 | { 5 | public QuickJSTypePrinter(BindingContext context) : base(context) 6 | { 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp: -------------------------------------------------------------------------------- 1 | #include "CppSharp_QuickJS.h" 2 | 3 | extern "C" 4 | { 5 | 6 | extern void register_signal(JSContext* ctx, JSModuleDef* m, bool set, int phase); 7 | 8 | void register_CppSharp_QuickJS(JSContext* ctx, JSModuleDef* m, bool set, int phase) 9 | { 10 | register_signal(ctx, m, set, phase); 11 | } 12 | 13 | } // extern "C" 14 | -------------------------------------------------------------------------------- /src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.h: -------------------------------------------------------------------------------- 1 | // ---------------------------------------------------------------------------- 2 | // 3 | // This is autogenerated code by CppSharp. 4 | // Do not edit this file or all your changes will be lost after re-generation. 5 | // 6 | // ---------------------------------------------------------------------------- 7 | #pragma once 8 | 9 | #include 10 | 11 | class Signal 12 | { 13 | public: 14 | 15 | Signal(); 16 | 17 | ~Signal(); 18 | 19 | int connect(void (*function)()); 20 | 21 | bool disconnect(int slot); 22 | 23 | bool isEmpty(); 24 | }; 25 | -------------------------------------------------------------------------------- /src/Generator/Generators/QuickJS/Runtime/premake5.lua: -------------------------------------------------------------------------------- 1 | project "cppsharp-quickjs-runtime" 2 | files { "" } -------------------------------------------------------------------------------- /src/Generator/Generators/TS/TSGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CppSharp.AST; 3 | using CppSharp.Generators.C; 4 | using CppSharp.Passes; 5 | 6 | namespace CppSharp.Generators.TS 7 | { 8 | /// 9 | /// C++ generator responsible for driving the generation of source and 10 | /// header files. 11 | /// 12 | public class TSGenerator : CGenerator 13 | { 14 | public TSGenerator(BindingContext context) : base(context) 15 | { 16 | } 17 | 18 | public override List Generate(IEnumerable units) 19 | { 20 | var outputs = new List(); 21 | 22 | var header = new TSSources(Context, units); 23 | outputs.Add(header); 24 | 25 | return outputs; 26 | } 27 | 28 | public override bool SetupPasses() 29 | { 30 | return true; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Generator/Passes/CheckKeywordNamesPass.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Generators.CSharp; 3 | 4 | namespace CppSharp.Passes 5 | { 6 | public class CheckKeywordNamesPass : TranslationUnitPass 7 | { 8 | public override bool VisitClassDecl(Class @class) 9 | { 10 | if (!base.VisitClassDecl(@class) || @class.Layout == null) 11 | return false; 12 | 13 | foreach (var field in @class.Layout.Fields) 14 | field.Name = SafeIdentifier(field.Name); 15 | 16 | return true; 17 | } 18 | 19 | public override bool VisitDeclaration(Declaration decl) 20 | { 21 | if (!base.VisitDeclaration(decl) || decl.Ignore) 22 | return false; 23 | 24 | decl.Name = SafeIdentifier(decl.Name); 25 | return true; 26 | } 27 | 28 | private string SafeIdentifier(string id) => 29 | Options.IsCLIGenerator ? id : CSharpSources.SafeIdentifier(id); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Generator/Passes/EqualiseAccessOfOverrideAndBasePass.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using CppSharp.AST; 4 | 5 | namespace CppSharp.Passes 6 | { 7 | public class EqualiseAccessOfOverrideAndBasePass : TranslationUnitPass 8 | { 9 | public EqualiseAccessOfOverrideAndBasePass() => VisitOptions.ResetFlags( 10 | VisitFlags.ClassMethods | VisitFlags.ClassTemplateSpecializations); 11 | 12 | public override bool VisitASTContext(ASTContext context) 13 | { 14 | var result = base.VisitASTContext(context); 15 | 16 | foreach (var baseOverride in basesOverrides) 17 | { 18 | var access = baseOverride.Value.Max(o => o.Access); 19 | foreach (var @override in baseOverride.Value) 20 | @override.Access = access; 21 | } 22 | 23 | return result; 24 | } 25 | 26 | public override bool VisitMethodDecl(Method method) 27 | { 28 | if (!base.VisitMethodDecl(method) || !method.IsOverride) 29 | return false; 30 | 31 | var baseMethod = method.GetRootBaseMethod(); 32 | if (!baseMethod.IsGenerated) 33 | return false; 34 | 35 | HashSet overrides; 36 | if (basesOverrides.ContainsKey(baseMethod)) 37 | overrides = basesOverrides[baseMethod]; 38 | else 39 | overrides = basesOverrides[baseMethod] = new HashSet { baseMethod }; 40 | overrides.Add(method); 41 | 42 | return true; 43 | } 44 | 45 | private Dictionary> basesOverrides = new Dictionary>(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Generator/Passes/ExtractInterfacePass.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | 3 | namespace CppSharp.Passes 4 | { 5 | public class ExtractInterfacePass : MultipleInheritancePass 6 | { 7 | /// 8 | /// Creates interface from generated classes 9 | /// 10 | 11 | public override bool VisitClassDecl(Class @class) 12 | { 13 | if (!@class.IsGenerated) 14 | return false; 15 | 16 | if (@class.IsInterface) 17 | { 18 | return false; 19 | } 20 | 21 | classesWithSecondaryBases.Add(@class); 22 | GetInterface(@class); 23 | return true; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Generator/Passes/FixDefaultParamValuesOfOverridesPass.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using CppSharp.AST; 3 | 4 | namespace CppSharp.Passes 5 | { 6 | public class FixDefaultParamValuesOfOverridesPass : TranslationUnitPass 7 | { 8 | public override bool VisitMethodDecl(Method method) 9 | { 10 | if (!method.IsOverride || method.IsSynthesized) 11 | return true; 12 | 13 | Method rootBaseMethod = method.GetRootBaseMethod(); 14 | var rootBaseParameters = rootBaseMethod.Parameters.Where( 15 | p => p.Kind != ParameterKind.IndirectReturnType).ToList(); 16 | var parameters = method.Parameters.Where( 17 | p => p.Kind != ParameterKind.IndirectReturnType).ToList(); 18 | for (int i = 0; i < parameters.Count; i++) 19 | { 20 | var rootBaseParameter = rootBaseParameters[i]; 21 | var parameter = parameters[i]; 22 | if (rootBaseParameter.DefaultArgument == null) 23 | parameter.DefaultArgument = null; 24 | else 25 | parameter.DefaultArgument = rootBaseParameter.DefaultArgument.Clone(); 26 | } 27 | 28 | return true; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Generator/Passes/HandleVariableInitializerPass.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Internal; 3 | 4 | namespace CppSharp.Passes 5 | { 6 | public class HandleVariableInitializerPass : TranslationUnitPass 7 | { 8 | public HandleVariableInitializerPass() 9 | => VisitOptions.ResetFlags(VisitFlags.NamespaceVariables); 10 | 11 | public override bool VisitVariableDecl(Variable variable) 12 | { 13 | if (AlreadyVisited(variable) || variable.Ignore || variable.Initializer == null) 14 | return false; 15 | 16 | string initializerString = variable.Initializer.String; 17 | ExpressionHelper.PrintExpression(Context, null, variable.Type, variable.Initializer, 18 | allowDefaultLiteral: true, ref initializerString); 19 | 20 | if (string.IsNullOrWhiteSpace(initializerString)) 21 | variable.Initializer = null; 22 | else 23 | variable.Initializer.String = initializerString; 24 | 25 | return true; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using CppSharp.AST; 4 | 5 | namespace CppSharp.Passes 6 | { 7 | public class MakeProtectedNestedTypesPublicPass : TranslationUnitPass 8 | { 9 | public MakeProtectedNestedTypesPublicPass() 10 | => VisitOptions.ResetFlags(VisitFlags.Default); 11 | 12 | public override bool VisitClassDecl(Class @class) 13 | { 14 | if (!base.VisitClassDecl(@class)) 15 | return false; 16 | 17 | (from d in ((IEnumerable)@class.Classes).Concat(@class.Enums) 18 | where d.Access == AccessSpecifier.Protected 19 | select d).All(d => { d.Access = AccessSpecifier.Public; return true; }); 20 | 21 | return true; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Generator/Passes/MarkEventsWithUniqueIdPass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using CppSharp.AST; 5 | using CppSharp.AST.Extensions; 6 | using CppSharp.Passes; 7 | using Type = CppSharp.AST.Type; 8 | 9 | namespace CppSharp 10 | { 11 | /// 12 | /// This pass sets each event in the AST with a global unique ID. 13 | /// 14 | public class MarkEventsWithUniqueIdPass : TranslationUnitPass 15 | { 16 | private int eventId = 1; 17 | public Dictionary EventIds = new Dictionary(); 18 | 19 | public override bool VisitEvent(Event @event) 20 | { 21 | if (AlreadyVisited(@event)) 22 | return true; 23 | 24 | if (@event.GlobalId != 0) 25 | throw new NotSupportedException(); 26 | 27 | @event.GlobalId = eventId++; 28 | return base.VisitEvent(@event); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/Generator/Passes/MarshalPrimitivePointersAsRefTypePass.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using CppSharp.AST; 3 | using CppSharp.AST.Extensions; 4 | using CppSharp.Generators; 5 | 6 | namespace CppSharp.Passes 7 | { 8 | public class MarshalPrimitivePointersAsRefTypePass : TranslationUnitPass 9 | { 10 | public MarshalPrimitivePointersAsRefTypePass() => VisitOptions.ResetFlags( 11 | VisitFlags.ClassMethods | VisitFlags.ClassTemplateSpecializations); 12 | 13 | public override bool VisitFunctionDecl(Function function) 14 | { 15 | if (!base.VisitFunctionDecl(function) || 16 | function.OperatorKind == CXXOperatorKind.Conversion || 17 | function.OperatorKind == CXXOperatorKind.ExplicitConversion) 18 | return false; 19 | 20 | foreach (var param in function.Parameters.Where( 21 | p => !p.IsOut && !p.QualifiedType.IsConstRefToPrimitive() && 22 | p.Type.Desugar().IsPrimitiveTypeConvertibleToRef())) 23 | param.Usage = ParameterUsage.InOut; 24 | 25 | return true; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Generator/Passes/MatchParamNamesWithInstantiatedFromPass.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using System; 3 | 4 | namespace CppSharp.Passes 5 | { 6 | /// 7 | /// Fixes a so far irreproducible bug where parameters in a template have names 8 | /// different from the ones the respective parameters have in the specializations. 9 | /// 10 | public class MatchParamNamesWithInstantiatedFromPass : TranslationUnitPass 11 | { 12 | public MatchParamNamesWithInstantiatedFromPass() => VisitOptions.ResetFlags( 13 | VisitFlags.ClassMethods | VisitFlags.NamespaceFunctions | 14 | VisitFlags.ClassTemplateSpecializations); 15 | 16 | public override bool VisitFunctionDecl(Function function) 17 | { 18 | if (!base.VisitFunctionDecl(function) || function.InstantiatedFrom == null || 19 | (function.Namespace is ClassTemplateSpecialization specialization && 20 | specialization.SpecializationKind == TemplateSpecializationKind.ExplicitSpecialization)) 21 | return false; 22 | int parameters = Math.Min(function.Parameters.Count, function.InstantiatedFrom.Parameters.Count); 23 | for (int i = 0; i < parameters; i++) 24 | function.InstantiatedFrom.Parameters[i].Name = function.Parameters[i].Name; 25 | 26 | return true; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/Generator/Passes/PassBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using CppSharp.Generators; 5 | using CppSharp.Passes; 6 | 7 | namespace CppSharp 8 | { 9 | /// 10 | /// This class is used to build passes that will be run against the AST 11 | /// that comes from C++. 12 | /// 13 | public class PassBuilder 14 | { 15 | public BindingContext Context { get; private set; } 16 | public List Passes { get; private set; } 17 | 18 | public PassBuilder(BindingContext context) 19 | { 20 | Context = context; 21 | Passes = new List(); 22 | } 23 | 24 | /// 25 | /// Adds a new pass to the builder. 26 | /// 27 | public void AddPass(T pass) 28 | { 29 | if (pass is TranslationUnitPass) 30 | (pass as TranslationUnitPass).Context = Context; 31 | 32 | Passes.Add(pass); 33 | } 34 | 35 | /// 36 | /// Remove a previously-added pass, if exists. 37 | /// 38 | public bool RemovePass(T pass) 39 | { 40 | return Passes.Remove(pass); 41 | } 42 | 43 | /// 44 | /// Finds a previously-added pass of the given type. 45 | /// 46 | public U FindPass() where U : TranslationUnitPass 47 | { 48 | return Passes.OfType().Select(pass => pass as U).FirstOrDefault(); 49 | } 50 | 51 | /// 52 | /// Runs the passes in the builder. 53 | /// 54 | public void RunPasses(Action action) 55 | { 56 | foreach (var pass in Passes) 57 | action(pass); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Generator/Types/DeclMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using CppSharp.AST; 3 | using CppSharp.Generators; 4 | using CppSharp.Generators.C; 5 | using Attribute = System.Attribute; 6 | 7 | namespace CppSharp.Types 8 | { 9 | /// 10 | /// Declaration maps allow customization of generated code, either 11 | /// partially or fully, depending on how its setup. 12 | /// 13 | public abstract class DeclMap 14 | { 15 | public BindingContext Context { get; set; } 16 | public IDeclMapDatabase DeclMapDatabase { get; set; } 17 | 18 | public bool IsEnabled { get; set; } = true; 19 | 20 | public virtual bool IsIgnored => false; 21 | 22 | public Declaration Declaration { get; set; } 23 | public DeclarationContext DeclarationContext { get; set; } 24 | 25 | public abstract Declaration GetDeclaration(); 26 | 27 | public virtual void Generate(CCodeGenerator generator) 28 | { 29 | 30 | } 31 | } 32 | 33 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] 34 | public class DeclMapAttribute : Attribute 35 | { 36 | public GeneratorKind GeneratorKind { get; set; } 37 | 38 | public DeclMapAttribute() 39 | { 40 | } 41 | 42 | public DeclMapAttribute(GeneratorKind generatorKind) 43 | { 44 | GeneratorKind = generatorKind; 45 | } 46 | } 47 | 48 | public interface IDeclMapDatabase 49 | { 50 | bool FindDeclMap(Declaration declaration, out DeclMap declMap); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Generator/Types/Std/Stdlib.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.Types.Std 2 | { 3 | [TypeMap("va_list")] 4 | public partial class VaList : TypeMap 5 | { 6 | public override bool IsIgnored => true; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Generator/Utils/FSM/ConsoleWriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CppSharp.Utils.FSM 4 | { 5 | public class ConsoleWriter 6 | { 7 | public static void Failure(string message) 8 | { 9 | Console.ForegroundColor = ConsoleColor.DarkRed; 10 | Write(message); 11 | } 12 | 13 | public static void Success(string message) 14 | { 15 | Console.ForegroundColor = ConsoleColor.DarkGreen; 16 | Write(message); 17 | } 18 | 19 | private static void Write(string message) 20 | { 21 | Console.WriteLine(message); 22 | Console.ResetColor(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Generator/Utils/FSM/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace CppSharp.Utils.FSM 4 | { 5 | internal class Program 6 | { 7 | private static void Main(string[] args) 8 | { 9 | var Q = new List { "q0", "q1" }; 10 | var Sigma = new List { '0', '1' }; 11 | var Delta = new List{ 12 | new Transition("q0", '0', "q0"), 13 | new Transition("q0", '1', "q1"), 14 | new Transition("q1", '1', "q1"), 15 | new Transition("q1", '0', "q0") 16 | }; 17 | var Q0 = new List { "q0" }; 18 | var F = new List { "q0", "q1" }; 19 | var DFSM = new DFSM(Q, Sigma, Delta, Q0, F); 20 | 21 | var minimizedDFSM = Minimize.MinimizeDFSM(DFSM); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/Generator/Utils/FSM/Transition.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.Utils.FSM 2 | { 3 | public class Transition 4 | { 5 | public string StartState { get; private set; } 6 | public char Symbol { get; private set; } 7 | public string EndState { get; private set; } 8 | 9 | public Transition(string startState, char symbol, string endState) 10 | { 11 | StartState = startState; 12 | Symbol = symbol; 13 | EndState = endState; 14 | } 15 | 16 | public override string ToString() 17 | { 18 | return string.Format("({0}, {1}) -> {2}\n", StartState, Symbol, EndState); 19 | } 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/Generator/Utils/IEnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CppSharp.Utils 5 | { 6 | public static class IEnumerableExtensions 7 | { 8 | public static IList TopologicalSort(this ICollection source, Func> dependencies, bool throwOnCycle = false) 9 | { 10 | var sorted = new List(); 11 | var visited = new HashSet(); 12 | 13 | foreach (var item in source) 14 | Visit(item, source, visited, sorted, dependencies, throwOnCycle); 15 | 16 | return sorted; 17 | } 18 | 19 | private static void Visit(T item, ICollection source, ISet visited, ICollection sorted, Func> dependencies, bool throwOnCycle) 20 | { 21 | if (!visited.Contains(item)) 22 | { 23 | visited.Add(item); 24 | 25 | foreach (var dep in dependencies(item)) 26 | Visit(dep, source, visited, sorted, dependencies, throwOnCycle); 27 | 28 | if (source.Contains(item)) 29 | { 30 | sorted.Add(item); 31 | } 32 | } 33 | else 34 | { 35 | if (throwOnCycle && !sorted.Contains(item)) 36 | throw new Exception("Cyclic dependency found"); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Generator/Utils/OrderedSet.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | 4 | namespace CppSharp.Utils 5 | { 6 | /// 7 | /// Works just like an HashSet but preserves insertion order. 8 | /// 9 | /// 10 | public class OrderedSet : ICollection 11 | { 12 | private readonly IDictionary> dictionary; 13 | private readonly LinkedList linkedList; 14 | 15 | public OrderedSet() 16 | : this(EqualityComparer.Default) 17 | { 18 | } 19 | 20 | public OrderedSet(IEqualityComparer comparer) 21 | { 22 | dictionary = new Dictionary>(comparer); 23 | linkedList = new LinkedList(); 24 | } 25 | 26 | public int Count 27 | { 28 | get { return dictionary.Count; } 29 | } 30 | 31 | public virtual bool IsReadOnly 32 | { 33 | get { return dictionary.IsReadOnly; } 34 | } 35 | 36 | void ICollection.Add(T item) 37 | { 38 | Add(item); 39 | } 40 | 41 | public bool Add(T item) 42 | { 43 | if (dictionary.ContainsKey(item)) return false; 44 | LinkedListNode node = linkedList.AddLast(item); 45 | dictionary.Add(item, node); 46 | return true; 47 | } 48 | 49 | public void Clear() 50 | { 51 | linkedList.Clear(); 52 | dictionary.Clear(); 53 | } 54 | 55 | public bool Remove(T item) 56 | { 57 | LinkedListNode node; 58 | bool found = dictionary.TryGetValue(item, out node); 59 | if (!found) return false; 60 | dictionary.Remove(item); 61 | linkedList.Remove(node); 62 | return true; 63 | } 64 | 65 | public IEnumerator GetEnumerator() 66 | { 67 | return linkedList.GetEnumerator(); 68 | } 69 | 70 | IEnumerator IEnumerable.GetEnumerator() 71 | { 72 | return GetEnumerator(); 73 | } 74 | 75 | public bool Contains(T item) 76 | { 77 | return dictionary.ContainsKey(item); 78 | } 79 | 80 | public void CopyTo(T[] array, int arrayIndex) 81 | { 82 | linkedList.CopyTo(array, arrayIndex); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Generator/Utils/ProcessHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Text; 3 | 4 | namespace CppSharp.Utils 5 | { 6 | public static class ProcessHelper 7 | { 8 | public static string Run(string path, string args, out int error, out string errorMessage) 9 | { 10 | return RunFrom(null, path, args, out error, out errorMessage); 11 | } 12 | 13 | public static string RunFrom(string workingDir, string path, string args, out int error, out string errorMessage) 14 | { 15 | using var process = new Process(); 16 | process.StartInfo.WorkingDirectory = workingDir; 17 | process.StartInfo.FileName = path; 18 | process.StartInfo.Arguments = args; 19 | process.StartInfo.UseShellExecute = false; 20 | process.StartInfo.RedirectStandardOutput = true; 21 | process.StartInfo.RedirectStandardError = true; 22 | 23 | var reterror = new StringBuilder(); 24 | var retout = new StringBuilder(); 25 | process.OutputDataReceived += (sender, outargs) => 26 | { 27 | if (string.IsNullOrEmpty(outargs.Data)) 28 | return; 29 | 30 | if (retout.Length > 0) 31 | retout.AppendLine(); 32 | retout.Append(outargs.Data); 33 | }; 34 | process.ErrorDataReceived += (sender, errargs) => 35 | { 36 | if (string.IsNullOrEmpty(errargs.Data)) 37 | return; 38 | 39 | if (reterror.Length > 0) 40 | reterror.AppendLine(); 41 | reterror.Append(errargs.Data); 42 | }; 43 | 44 | process.Start(); 45 | process.BeginOutputReadLine(); 46 | process.BeginErrorReadLine(); 47 | process.WaitForExit(); 48 | process.CancelOutputRead(); 49 | process.CancelErrorRead(); 50 | 51 | error = process.ExitCode; 52 | errorMessage = reterror.ToString(); 53 | return retout.ToString(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Generator/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.Generator") -------------------------------------------------------------------------------- /src/Package/CppSharp.Package.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | CppSharp 4 | true 5 | CppSharp is a tool and set of libraries which allows programmers to use C/C++ libraries with high-level programming languages (such as C#). 6 | 7 | It is a tool that takes C/C++ header and library files and generates the necessary glue to surface the native API as a managed API. Such an API can be used to consume an existing native library in your high-level code or add scripting support to a native codebase. 8 | 9 | The supported target languages at present are C# and C++/CLI. 10 | 11 | It can also be used as a library to parse native code into a syntax tree with a rich declaration and type information model. 12 | https://github.com/mono/CppSharp/CHANGELOG.md 13 | NU5131 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Parser/BuildConfig.cs: -------------------------------------------------------------------------------- 1 | namespace CppSharp.Parser 2 | { 3 | public static class BuildConfig 4 | { 5 | public const string Choice = "default"; 6 | } 7 | } -------------------------------------------------------------------------------- /src/Parser/CppSharp.Parser.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | true 4 | true 5 | true 6 | dll 7 | so 8 | dylib 9 | lib 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 | -------------------------------------------------------------------------------- /src/Parser/premake5.lua: -------------------------------------------------------------------------------- 1 | local buildconfig = path.join(actionbuilddir, "BuildConfig.cs") 2 | 3 | local function GenerateBuildConfig() 4 | print("Generating CppSharp build configuration file 'BuildConfig.cs'") 5 | 6 | local file = io.open(buildconfig, "w+") 7 | file:write("namespace CppSharp.Parser", "\n{\n ") 8 | file:write("public static class BuildConfig", "\n {\n ") 9 | file:write("public const string Choice = \"" .. _ACTION .. "\";\n") 10 | file:write(" }\n}") 11 | file:close() 12 | end 13 | 14 | if generate_build_config == true and _ACTION then 15 | GenerateBuildConfig() 16 | end 17 | 18 | SetupExternalManagedProject("CppSharp.Parser") 19 | -------------------------------------------------------------------------------- /src/Runtime/CppSharp.Runtime.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 7.3 4 | true 5 | netstandard2.1 6 | true 7 | true 8 | 9 | -------------------------------------------------------------------------------- /src/Runtime/MarshalUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Text; 4 | 5 | namespace CppSharp.Runtime 6 | { 7 | public unsafe static class MarshalUtil 8 | { 9 | public static string GetString(Encoding encoding, IntPtr str) 10 | { 11 | if (str == IntPtr.Zero) 12 | return null; 13 | 14 | int byteCount = 0; 15 | 16 | if (encoding == Encoding.UTF32) 17 | { 18 | var str32 = (int*)str; 19 | while (*(str32++) != 0) byteCount += sizeof(int); 20 | } 21 | else if (encoding == Encoding.Unicode || encoding == Encoding.BigEndianUnicode) 22 | { 23 | var str16 = (short*)str; 24 | while (*(str16++) != 0) byteCount += sizeof(short); 25 | } 26 | else 27 | { 28 | var str8 = (byte*)str; 29 | while (*(str8++) != 0) byteCount += sizeof(byte); 30 | } 31 | 32 | return encoding.GetString((byte*)str, byteCount); 33 | } 34 | 35 | public static T[] GetArray(void* array, int size) where T : unmanaged 36 | { 37 | if (array == null) 38 | return null; 39 | var result = new T[size]; 40 | fixed (void* fixedResult = result) 41 | Buffer.MemoryCopy(array, fixedResult, sizeof(T) * size, sizeof(T) * size); 42 | return result; 43 | } 44 | 45 | public static char[] GetCharArray(sbyte* array, int size) 46 | { 47 | if (array == null) 48 | return null; 49 | var result = new char[size]; 50 | for (var i = 0; i < size; ++i) 51 | result[i] = Convert.ToChar(array[i]); 52 | return result; 53 | } 54 | 55 | public static IntPtr[] GetIntPtrArray(IntPtr* array, int size) 56 | { 57 | return GetArray(array, size); 58 | } 59 | 60 | public static T GetDelegate(IntPtr[] vtables, short table, int i) where T : class 61 | { 62 | var slot = *(IntPtr*)(vtables[table] + i * sizeof(IntPtr)); 63 | return Marshal.GetDelegateForFunctionPointer(slot); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/Runtime/Pointer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CppSharp.Runtime 4 | { 5 | public class Pointer 6 | { 7 | public Pointer(IntPtr ptr) => this.ptr = ptr; 8 | 9 | public static implicit operator IntPtr(Pointer pointer) => pointer.ptr; 10 | 11 | private readonly IntPtr ptr; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Runtime/SafeUnmanagedMemoryHandle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Security.Permissions; 4 | using Microsoft.Win32.SafeHandles; 5 | 6 | namespace CppSharp.Runtime 7 | { 8 | // https://stackoverflow.com/a/17563315/ 9 | [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] 10 | public sealed class SafeUnmanagedMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid 11 | { 12 | public SafeUnmanagedMemoryHandle() : base(true) { } 13 | 14 | public SafeUnmanagedMemoryHandle(IntPtr preexistingHandle, bool ownsHandle) 15 | : base(ownsHandle) => SetHandle(preexistingHandle); 16 | 17 | protected override bool ReleaseHandle() 18 | { 19 | if (handle != IntPtr.Zero) 20 | { 21 | Marshal.FreeHGlobal(handle); 22 | handle = IntPtr.Zero; 23 | return true; 24 | } 25 | return false; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Runtime/UTF32Marshaller.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Text; 4 | 5 | namespace CppSharp.Runtime 6 | { 7 | public class UTF32Marshaller : ICustomMarshaler 8 | { 9 | static private UTF32Marshaller marshaler; 10 | 11 | public unsafe object MarshalNativeToManaged(IntPtr pNativeData) 12 | { 13 | var p = (Int32*)pNativeData; 14 | int count = 0; 15 | while (*p++ != 0) 16 | ++count; 17 | return Encoding.UTF32.GetString((byte*)pNativeData, count * 4); 18 | } 19 | 20 | public unsafe IntPtr MarshalManagedToNative(object ManagedObj) 21 | { 22 | if (!(ManagedObj is string @string)) 23 | return IntPtr.Zero; 24 | 25 | var capacity = @string.Length * 4 + 4; 26 | var result = Marshal.AllocCoTaskMem(capacity); 27 | var byteCount = 0; 28 | fixed (char* stringPtr = @string) 29 | byteCount = Encoding.UTF32.GetBytes(stringPtr, @string.Length, (byte*)result, capacity); 30 | *(Int32*)(result + byteCount) = 0; 31 | return result; 32 | } 33 | 34 | public void CleanUpNativeData(IntPtr pNativeData) 35 | { 36 | Marshal.FreeCoTaskMem(pNativeData); 37 | } 38 | 39 | public void CleanUpManagedData(object ManagedObj) 40 | { 41 | } 42 | 43 | public int GetNativeDataSize() 44 | { 45 | return -1; 46 | } 47 | 48 | public static ICustomMarshaler GetInstance(string pstrCookie) 49 | { 50 | if (marshaler == null) 51 | marshaler = new UTF32Marshaller(); 52 | return marshaler; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Runtime/UTF8Marshaller.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Text; 4 | 5 | namespace CppSharp.Runtime 6 | { 7 | // HACK: .NET Standard 2.0 which we use in auto-building to support .NET Framework, lacks UnmanagedType.LPUTF8Str 8 | public class UTF8Marshaller : ICustomMarshaler 9 | { 10 | public void CleanUpManagedData(object ManagedObj) 11 | { 12 | } 13 | 14 | public void CleanUpNativeData(IntPtr pNativeData) 15 | => Marshal.FreeHGlobal(pNativeData); 16 | 17 | public int GetNativeDataSize() => -1; 18 | 19 | public IntPtr MarshalManagedToNative(object managedObj) 20 | { 21 | if (managedObj == null) 22 | return IntPtr.Zero; 23 | if (!(managedObj is string)) 24 | throw new MarshalDirectiveException( 25 | "UTF8Marshaler must be used on a string."); 26 | 27 | // not null terminated 28 | byte[] strbuf = Encoding.UTF8.GetBytes((string)managedObj); 29 | IntPtr buffer = Marshal.AllocHGlobal(strbuf.Length + 1); 30 | Marshal.Copy(strbuf, 0, buffer, strbuf.Length); 31 | 32 | // write the terminating null 33 | Marshal.WriteByte(buffer + strbuf.Length, 0); 34 | return buffer; 35 | } 36 | 37 | public unsafe object MarshalNativeToManaged(IntPtr str) 38 | { 39 | if (str == IntPtr.Zero) 40 | return null; 41 | 42 | int byteCount = 0; 43 | var str8 = (byte*)str; 44 | while (*(str8++) != 0) byteCount += sizeof(byte); 45 | 46 | return Encoding.UTF8.GetString((byte*)str, byteCount); 47 | } 48 | 49 | public static ICustomMarshaler GetInstance(string pstrCookie) 50 | { 51 | if (marshaler == null) 52 | marshaler = new UTF8Marshaller(); 53 | return marshaler; 54 | } 55 | 56 | private static UTF8Marshaller marshaler; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Runtime/VTables.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Runtime.InteropServices; 5 | 6 | namespace CppSharp.Runtime 7 | { 8 | public struct VTables 9 | { 10 | public Delegate[][] Methods { get; set; } 11 | public IntPtr[] Tables { get; set; } 12 | private ConcurrentDictionary<(short, short, int), Delegate> Specializations; 13 | 14 | public VTables(IntPtr[] tables, Delegate[][] methods = null) 15 | { 16 | Tables = tables; 17 | Methods = methods; 18 | Specializations = null; 19 | } 20 | 21 | public bool IsEmpty => Tables == null; 22 | public bool IsTransient => Methods == null; 23 | 24 | public T GetMethodDelegate(short table, int slot, short specialiation = 0) where T : Delegate 25 | { 26 | if (specialiation == 0 && !IsTransient) 27 | { 28 | var method = Methods[table][slot]; 29 | 30 | if (method == null) 31 | Methods[table][slot] = method = MarshalUtil.GetDelegate(Tables, table, slot); 32 | 33 | return (T)method; 34 | } 35 | else 36 | { 37 | if (Specializations == null) 38 | Specializations = new ConcurrentDictionary<(short, short, int), Delegate>(); 39 | 40 | var key = (specialiation, table, slot); 41 | 42 | if (!Specializations.TryGetValue(key, out var method)) 43 | Specializations[key] = method = MarshalUtil.GetDelegate(Tables, table, slot); 44 | 45 | return (T)method; 46 | } 47 | } 48 | 49 | public unsafe static IntPtr* CloneTable(List cache, IntPtr instance, int offset, int size, int offsetRTTI) 50 | { 51 | var sizeInBytes = (size + offsetRTTI) * sizeof(IntPtr); 52 | var src = (((*(IntPtr*)instance) + offset) - offsetRTTI * sizeof(IntPtr)).ToPointer(); 53 | var entries = (IntPtr*)Marshal.AllocHGlobal(sizeInBytes); 54 | 55 | Buffer.MemoryCopy(src, entries, sizeInBytes, sizeInBytes); 56 | cache.Add(new SafeUnmanagedMemoryHandle((IntPtr)entries, true)); 57 | return entries + offsetRTTI; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Runtime/premake5.lua: -------------------------------------------------------------------------------- 1 | SetupExternalManagedProject("CppSharp.Runtime") 2 | 3 | -------------------------------------------------------------------------------- /tests/Classes.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Classes2.h" 4 | 5 | class Class 6 | { 7 | public: 8 | void ReturnsVoid() {} 9 | int ReturnsInt() const { return 0; } 10 | Class* PassAndReturnsClassPtr(Class* obj) { return obj; } 11 | }; 12 | 13 | class ClassWithField 14 | { 15 | public: 16 | ClassWithField() 17 | : Field(10) 18 | { 19 | } 20 | int Field; 21 | int ReturnsField() const { return Field; } 22 | }; 23 | 24 | class ClassWithProperty 25 | { 26 | public: 27 | ClassWithProperty() 28 | : Field(10) 29 | { 30 | } 31 | int GetField() const { return Field; } 32 | void SetField(int value) { Field = value; } 33 | 34 | private: 35 | int Field; 36 | }; 37 | 38 | class ClassWithOverloads 39 | { 40 | public: 41 | ClassWithOverloads() {} 42 | ClassWithOverloads(int) {} 43 | void Overload() {} 44 | void Overload(int) {} 45 | }; 46 | 47 | class ClassWithSingleInheritance : public Class 48 | { 49 | public: 50 | int ChildMethod() { return 2; } 51 | }; 52 | 53 | class ClassWithExternalInheritance : public ClassFromAnotherUnit 54 | { 55 | }; 56 | 57 | // void FunctionPassClassByRef(Class* klass) { } 58 | // Class* FunctionReturnsClassByRef() { return new Class(); } 59 | -------------------------------------------------------------------------------- /tests/Classes2.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class ClassFromAnotherUnit 4 | { 5 | }; 6 | -------------------------------------------------------------------------------- /tests/Delegates.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | using namespace fastdelegate; 6 | 7 | class ClassWithDelegate 8 | { 9 | public: 10 | ClassWithDelegate() {} 11 | FastDelegate OnEvent0; 12 | void FireEvent0(int value) 13 | { 14 | if (OnEvent0) 15 | OnEvent0(value); 16 | } 17 | }; 18 | 19 | class ClassInheritsDelegate : public ClassWithDelegate 20 | { 21 | }; 22 | -------------------------------------------------------------------------------- /tests/Enums.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | enum class Enum0 4 | { 5 | Item0, 6 | Item1, 7 | Item2 = 5 8 | }; 9 | 10 | Enum0 ReturnsEnum() 11 | { 12 | return Enum0::Item0; 13 | } 14 | Enum0 PassAndReturnsEnum(Enum0 e) 15 | { 16 | return e; 17 | } -------------------------------------------------------------------------------- /tests/Overloads.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | void Overload0() {} 4 | 5 | int Overload1() 6 | { 7 | return 1; 8 | } 9 | int Overload1(int) 10 | { 11 | return 2; 12 | } 13 | 14 | int Overload(int, int) 15 | { 16 | return 1; 17 | } 18 | int Overload(int, float) 19 | { 20 | return 2; 21 | } 22 | int Overload(float, int) 23 | { 24 | return 3; 25 | } 26 | 27 | int DefaultParamsOverload() 28 | { 29 | return 0; 30 | } 31 | int DefaultParamsOverload(int a, int b) 32 | { 33 | return 2; 34 | } 35 | int DefaultParamsOverload(int a, float b = 2) 36 | { 37 | return 3; 38 | } 39 | 40 | int DefaultParamsOverload2(int a = 0, int b = 0, int c = 0) 41 | { 42 | return 1; 43 | } 44 | -------------------------------------------------------------------------------- /tests/dotnet/CLI/CLI.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/CLI/CLI.Tests.CLI.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/CLI/CLI.cpp: -------------------------------------------------------------------------------- 1 | #include "CLI.h" 2 | 3 | int Types::AttributedSum(int A, int B) 4 | { 5 | return A + B; 6 | } 7 | 8 | TestProtectedDestructors::~TestProtectedDestructors() {} 9 | 10 | std::string Date::testStdString(std::string s) 11 | { 12 | return s + "_test"; 13 | } 14 | 15 | void testFreeFunction() 16 | { 17 | 18 | } 19 | 20 | struct IncompleteStruct {}; 21 | 22 | IncompleteStruct* createIncompleteStruct() 23 | { 24 | return new IncompleteStruct(); 25 | } 26 | 27 | DLL_API void useIncompleteStruct(IncompleteStruct * a) 28 | { 29 | return; 30 | } 31 | 32 | TestMappedTypeNonConstRefParam::TestMappedTypeNonConstRefParam(const std::string str) 33 | { 34 | m_str = str; 35 | } 36 | 37 | const TestMappedTypeNonConstRefParam & TestMappedTypeNonConstRefParam::operator=(const std::string str) 38 | { 39 | m_str = str; 40 | 41 | return *this; 42 | } 43 | 44 | void TestMappedTypeNonConstRefParamConsumer::ChangePassedMappedTypeNonConstRefParam(TestMappedTypeNonConstRefParam & v) 45 | { 46 | v = "ChangePassedMappedTypeNonConstRefParam"; 47 | } 48 | 49 | VectorPointerGetter::VectorPointerGetter() 50 | { 51 | vecPtr = new std::vector(); 52 | vecPtr->push_back("VectorPointerGetter"); 53 | } 54 | 55 | VectorPointerGetter::~VectorPointerGetter() 56 | { 57 | if (vecPtr) 58 | { 59 | auto tempVec = vecPtr; 60 | delete vecPtr; 61 | tempVec = nullptr; 62 | } 63 | } 64 | 65 | std::vector* VectorPointerGetter::GetVecPtr() 66 | { 67 | return vecPtr; 68 | } 69 | 70 | std::string DLL_API MultipleConstantArraysParamsTestMethod(char arr1[9], char arr2[10]) 71 | { 72 | return std::string(arr1, arr1 + 9) + std::string(arr2, arr2 + 10); 73 | } 74 | 75 | std::string DLL_API StructWithNestedUnionTestMethod(StructWithNestedUnion val) 76 | { 77 | return std::string(val.nestedUnion.szText, val.nestedUnion.szText + 10); 78 | } 79 | 80 | std::string DLL_API UnionWithNestedStructTestMethod(UnionWithNestedStruct val) 81 | { 82 | return std::string(val.nestedStruct.szText, val.nestedStruct.szText + 10); 83 | } 84 | 85 | std::string DLL_API UnionWithNestedStructArrayTestMethod(UnionWithNestedStructArray arr) 86 | { 87 | return std::string(arr.nestedStructs[0].szText, arr.nestedStructs[0].szText + 10) 88 | + std::string(arr.nestedStructs[1].szText, arr.nestedStructs[1].szText + 10); 89 | } -------------------------------------------------------------------------------- /tests/dotnet/CLI/NestedEnumInClassTest/ClassWithNestedEnum.cpp: -------------------------------------------------------------------------------- 1 | #include "ClassWithNestedEnum.h" -------------------------------------------------------------------------------- /tests/dotnet/CLI/NestedEnumInClassTest/ClassWithNestedEnum.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../../Tests.h" 4 | 5 | class DLL_API ClassWithNestedEnum 6 | { 7 | public: 8 | enum NestedEnum 9 | { 10 | E1, 11 | E2 12 | }; 13 | }; 14 | -------------------------------------------------------------------------------- /tests/dotnet/CLI/NestedEnumInClassTest/NestedEnumConsumer.cpp: -------------------------------------------------------------------------------- 1 | #include "NestedEnumConsumer.h" 2 | 3 | ClassWithNestedEnum::NestedEnum NestedEnumConsumer::GetPassedEnum(ClassWithNestedEnum::NestedEnum e) 4 | { 5 | return e; 6 | } 7 | -------------------------------------------------------------------------------- /tests/dotnet/CLI/NestedEnumInClassTest/NestedEnumConsumer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../../Tests.h" 4 | 5 | #include "ClassWithNestedEnum.h" 6 | 7 | class DLL_API NestedEnumConsumer 8 | { 9 | public: 10 | ClassWithNestedEnum::NestedEnum GetPassedEnum(ClassWithNestedEnum::NestedEnum e); 11 | }; -------------------------------------------------------------------------------- /tests/dotnet/CLI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "CLI.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/CLI/UseTemplateTypeFromIgnoredClassTemplate/Employee.cpp: -------------------------------------------------------------------------------- 1 | #include "Employee.h" 2 | 3 | std::string Employee::GetName() 4 | { 5 | return "Employee"; 6 | } -------------------------------------------------------------------------------- /tests/dotnet/CLI/UseTemplateTypeFromIgnoredClassTemplate/Employee.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../../Tests.h" 4 | #include 5 | 6 | class DLL_API Employee 7 | { 8 | public: 9 | virtual std::string GetName(); 10 | }; -------------------------------------------------------------------------------- /tests/dotnet/CLI/UseTemplateTypeFromIgnoredClassTemplate/EmployeeForwardDecl.h: -------------------------------------------------------------------------------- 1 | #include "IgnoredClassTemplateForEmployee.h" 2 | 3 | class Employee; 4 | typedef IgnoredClassTemplateForEmployee EmployeeTypedef; 5 | -------------------------------------------------------------------------------- /tests/dotnet/CLI/UseTemplateTypeFromIgnoredClassTemplate/EmployeeOrg.cpp: -------------------------------------------------------------------------------- 1 | #include "EmployeeOrg.h" 2 | 3 | #include "Employee.h" 4 | 5 | EmployeeTypedef EmployeeOrg::GetEmployee() 6 | { 7 | return IgnoredClassTemplateForEmployee(new Employee()); 8 | } 9 | 10 | void EmployeeOrg::DoSomething() 11 | { 12 | 13 | } -------------------------------------------------------------------------------- /tests/dotnet/CLI/UseTemplateTypeFromIgnoredClassTemplate/EmployeeOrg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../../Tests.h" 4 | 5 | #include "EmployeeForwardDecl.h" 6 | 7 | class DLL_API EmployeeOrg 8 | { 9 | public: 10 | void DoSomething(); 11 | 12 | EmployeeTypedef GetEmployee(); 13 | }; -------------------------------------------------------------------------------- /tests/dotnet/CLI/UseTemplateTypeFromIgnoredClassTemplate/IgnoredClassTemplateForEmployee.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | template 4 | class IgnoredClassTemplateForEmployee 5 | { 6 | public: 7 | IgnoredClassTemplateForEmployee(EmployeeT* employee) 8 | : m_employee(employee) 9 | { 10 | } 11 | 12 | EmployeeT* m_employee; 13 | }; -------------------------------------------------------------------------------- /tests/dotnet/CLI/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/CLI" 2 | SetupTestCLI("CLI", { "Employee", "EmployeeOrg", "ClassWithNestedEnum", "NestedEnumConsumer" }) -------------------------------------------------------------------------------- /tests/dotnet/CSharp/AnotherUnit.cpp: -------------------------------------------------------------------------------- 1 | #include "AnotherUnit.h" 2 | 3 | void SecondaryBase::VirtualMember() 4 | { 5 | } 6 | 7 | int SecondaryBase::property() 8 | { 9 | return 0; 10 | } 11 | 12 | void SecondaryBase::setProperty(int value) 13 | { 14 | } 15 | 16 | void SecondaryBase::function(bool* ok) 17 | { 18 | } 19 | 20 | void SecondaryBase::protectedFunction() 21 | { 22 | } 23 | 24 | int SecondaryBase::protectedProperty() 25 | { 26 | return 0; 27 | } 28 | 29 | void SecondaryBase::setProtectedProperty(int value) 30 | { 31 | } 32 | 33 | void functionInAnotherUnit() 34 | { 35 | } 36 | 37 | MultipleInheritance::MultipleInheritance() 38 | { 39 | } 40 | 41 | MultipleInheritance::~MultipleInheritance() 42 | { 43 | } 44 | 45 | namespace HasFreeConstant { 46 | extern const int DLL_API FREE_CONSTANT_IN_NAMESPACE = 5; 47 | extern const std::string DLL_API STD_STRING_CONSTANT = "test"; 48 | } // namespace HasFreeConstant 49 | -------------------------------------------------------------------------------- /tests/dotnet/CSharp/AnotherUnit.h: -------------------------------------------------------------------------------- 1 | #include "../Tests.h" 2 | #include 3 | 4 | #pragma once 5 | 6 | class DLL_API SecondaryBase 7 | { 8 | public: 9 | enum Property 10 | { 11 | P1, 12 | P2 13 | }; 14 | enum Function 15 | { 16 | M1, 17 | M2 18 | }; 19 | 20 | virtual void VirtualMember(); 21 | int property(); 22 | void setProperty(int value); 23 | void function(bool* ok = 0); 24 | typedef void HasPointerToEnum(Property* pointerToEnum); 25 | HasPointerToEnum* hasPointerToEnum; 26 | 27 | protected: 28 | void protectedFunction(); 29 | int protectedProperty(); 30 | void setProtectedProperty(int value); 31 | }; 32 | 33 | void DLL_API functionInAnotherUnit(); 34 | 35 | struct DLL_API ForwardDeclaredStruct; 36 | 37 | struct DLL_API DuplicateDeclaredStruct; 38 | 39 | template 40 | class DLL_API TemplateInAnotherUnit 41 | { 42 | T field; 43 | }; 44 | 45 | class ForwardInOtherUnitButSameModule 46 | { 47 | }; 48 | 49 | class DLL_API MultipleInheritance : ForwardInOtherUnitButSameModule, SecondaryBase 50 | { 51 | public: 52 | MultipleInheritance(); 53 | ~MultipleInheritance(); 54 | }; 55 | 56 | namespace HasFreeConstant { 57 | extern const int DLL_API FREE_CONSTANT_IN_NAMESPACE; 58 | extern const std::string DLL_API STD_STRING_CONSTANT; 59 | } // namespace HasFreeConstant 60 | -------------------------------------------------------------------------------- /tests/dotnet/CSharp/CSharp.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 0108 4 | 10 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /tests/dotnet/CSharp/CSharp.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/CSharp/CSharp.Tests.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/CSharp/CSharpPartialMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace CSharp 6 | { 7 | public partial class TestFinalizer 8 | { 9 | public static Action DisposeCallback { get; set; } 10 | 11 | partial void DisposePartial(bool disposing) 12 | { 13 | DisposeCallback?.Invoke(disposing, __Instance); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tests/dotnet/CSharp/ExcludedUnit.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class ClassUsingUnion 4 | { 5 | public: 6 | union 7 | { 8 | float arr[2]; 9 | struct 10 | { 11 | float a, b; 12 | }; 13 | }; 14 | }; 15 | -------------------------------------------------------------------------------- /tests/dotnet/CSharp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "CSharp.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/CSharp/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/CSharp" 2 | SetupTestCSharp("CSharp") -------------------------------------------------------------------------------- /tests/dotnet/Common/AnotherUnit.cpp: -------------------------------------------------------------------------------- 1 | #include "AnotherUnit.h" 2 | 3 | void DelegateNamespace::Nested::f3(void (*)()) 4 | { 5 | } 6 | 7 | void DelegateNamespace::f4(void (*)()) 8 | { 9 | } 10 | 11 | void AnotherUnit::f() 12 | { 13 | } 14 | -------------------------------------------------------------------------------- /tests/dotnet/Common/AnotherUnit.h: -------------------------------------------------------------------------------- 1 | #include "../Tests.h" 2 | 3 | // Verifies the header is included when the delegate is defined in a different file 4 | typedef void (*DelegateInAnotherUnit)(); 5 | 6 | // Tests automatic generation of anonymous delegates in different translation units 7 | namespace DelegateNamespace { 8 | namespace Nested { 9 | void DLL_API f3(void (*)()); 10 | } 11 | 12 | void DLL_API f4(void (*)()); 13 | } // namespace DelegateNamespace 14 | 15 | namespace AnotherUnit { 16 | void DLL_API f(); 17 | } 18 | -------------------------------------------------------------------------------- /tests/dotnet/Common/Common.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 11.0 4 | 5 | -------------------------------------------------------------------------------- /tests/dotnet/Common/Common.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/Common/Common.Tests.CLI.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/Common/Common.Tests.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/Common/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Common.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/Common/interface.h: -------------------------------------------------------------------------------- 1 | void Func(); 2 | -------------------------------------------------------------------------------- /tests/dotnet/Common/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/Common" 2 | SetupTestProject("Common", { "AnotherUnit" } , "_GenerateName") -------------------------------------------------------------------------------- /tests/dotnet/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /tests/dotnet/Empty/Empty.Gen.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Generators; 3 | using CppSharp.Utils; 4 | 5 | namespace CppSharp.Tests 6 | { 7 | public class EmptyTestsGenerator : GeneratorTest 8 | { 9 | public EmptyTestsGenerator(GeneratorKind kind) 10 | : base("Empty", kind) 11 | { 12 | } 13 | 14 | public override void Setup(Driver driver) 15 | { 16 | base.Setup(driver); 17 | driver.Options.OutputNamespace = "EmptyTest"; 18 | } 19 | 20 | public override void SetupPasses(Driver driver) 21 | { 22 | } 23 | 24 | public override void Preprocess(Driver driver, ASTContext ctx) 25 | { 26 | } 27 | 28 | public static void Main(string[] args) 29 | { 30 | ConsoleDriver.Run(new EmptyTestsGenerator(GeneratorKind.CSharp)); 31 | ConsoleDriver.Run(new EmptyTestsGenerator(GeneratorKind.CLI)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/dotnet/Empty/Empty.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using EmptyTest; 3 | using CppSharp.Utils; 4 | using NUnit.Framework; 5 | 6 | [TestFixture] 7 | public class EmptyTests : GeneratorTestFixture 8 | { 9 | } 10 | -------------------------------------------------------------------------------- /tests/dotnet/Empty/Empty.cpp: -------------------------------------------------------------------------------- 1 | #include "Empty.h" 2 | -------------------------------------------------------------------------------- /tests/dotnet/Empty/Empty.h: -------------------------------------------------------------------------------- 1 | #include "../Tests.h" 2 | -------------------------------------------------------------------------------- /tests/dotnet/Empty/premake4.lua: -------------------------------------------------------------------------------- 1 | --group "Tests/Empty" 2 | -- SetupTestProject("Empty") -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.Gen.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using CppSharp.AST; 3 | using CppSharp.Generators; 4 | using CppSharp.Utils; 5 | 6 | namespace CppSharp.Tests 7 | { 8 | public class EncodingsTestsGenerator : GeneratorTest 9 | { 10 | public EncodingsTestsGenerator(GeneratorKind kind) 11 | : base("Encodings", kind) 12 | { 13 | } 14 | 15 | public override void SetupPasses(Driver driver) 16 | { 17 | driver.Options.Encoding = Encoding.Unicode; 18 | } 19 | 20 | public override void Preprocess(Driver driver, ASTContext ctx) 21 | { 22 | 23 | } 24 | 25 | public static void Main(string[] args) 26 | { 27 | ConsoleDriver.Run(new EncodingsTestsGenerator(GeneratorKind.CSharp)); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.Tests.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.Tests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using Foo = Encodings.Foo; 3 | 4 | [TestFixture] 5 | public class EncodingsTests 6 | { 7 | [Test] 8 | public void TestFoo() 9 | { 10 | using (var foo = new Foo()) 11 | { 12 | const string georgia = "საქართველო"; 13 | foo.Unicode = georgia; 14 | Assert.That(foo.Unicode, Is.EqualTo(georgia)); 15 | 16 | // TODO: move this, it has nothing to do with Unicode, it's here only not to break the CLI branch 17 | Assert.That(foo[0], Is.EqualTo(5)); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.cpp: -------------------------------------------------------------------------------- 1 | #include "Encodings.h" 2 | 3 | std::string Foo::StringVariable = ""; 4 | 5 | // TODO: move this, it has nothing to do with Unicode, it's here only not to break the CLI branch 6 | int Foo::operator[](int i) const 7 | { 8 | return 5; 9 | } 10 | 11 | int Foo::operator[](int i) 12 | { 13 | return 5; 14 | } 15 | -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Encodings.h: -------------------------------------------------------------------------------- 1 | #include "../Tests.h" 2 | #include 3 | 4 | class DLL_API Foo 5 | { 6 | public: 7 | const char* Unicode; 8 | static std::string StringVariable; 9 | 10 | // TODO: VC++ does not support char16 11 | // char16 chr16; 12 | 13 | // TODO: move this, it has nothing to do with Unicode, it's here only not to break the CLI branch 14 | int operator[](int i) const; 15 | int operator[](int i); 16 | }; 17 | 18 | DLL_API int FooCallFoo(Foo* foo); 19 | -------------------------------------------------------------------------------- /tests/dotnet/Encodings/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Encodings.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/Encodings/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/Encodings" 2 | SetupTestCSharp("Encodings") -------------------------------------------------------------------------------- /tests/dotnet/NamespacesBase/NamespacesBase.cpp: -------------------------------------------------------------------------------- 1 | #include "NamespacesBase.h" 2 | 3 | 4 | Base::Base(int i) 5 | { 6 | b = i; 7 | } 8 | 9 | 10 | Base::Base() 11 | { 12 | } 13 | 14 | int Base::parent() 15 | { 16 | return 0; 17 | } 18 | 19 | Base2::Base2() 20 | : Base() 21 | { 22 | } 23 | 24 | Base2::Base2(int i) 25 | : Base(i) 26 | { 27 | } 28 | 29 | void Base2::parent(int i) 30 | { 31 | } 32 | 33 | HasVirtualInCore::HasVirtualInCore() 34 | { 35 | } 36 | 37 | HasVirtualInCore::HasVirtualInCore(TemplateClass t) 38 | { 39 | } 40 | 41 | int HasVirtualInCore::virtualInCore(int parameter) 42 | { 43 | return 1; 44 | } 45 | 46 | void SecondaryBase::function() 47 | { 48 | } 49 | -------------------------------------------------------------------------------- /tests/dotnet/NamespacesBase/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/Namespaces" 2 | SetupTestNativeProject("NamespacesBase") 3 | targetdir (path.join(gendir, "NamespacesDerived")) -------------------------------------------------------------------------------- /tests/dotnet/NamespacesBase/test.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mono/CppSharp/e093f713b90d49528de13afd859e3d1f34cf3049/tests/dotnet/NamespacesBase/test.cs -------------------------------------------------------------------------------- /tests/dotnet/NamespacesDerived/Independent.h: -------------------------------------------------------------------------------- 1 | class Derived; 2 | template 3 | class DependentFields; 4 | typedef DependentFields ForwardedInIndependentHeader; -------------------------------------------------------------------------------- /tests/dotnet/NamespacesDerived/NamespacesDerived.Gen.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Linq; 3 | using CppSharp.AST; 4 | using CppSharp.Generators; 5 | using CppSharp.Utils; 6 | 7 | namespace CppSharp.Tests 8 | { 9 | public class NamespacesDerivedTests : GeneratorTest 10 | { 11 | public NamespacesDerivedTests(GeneratorKind kind) 12 | : base("NamespacesDerived", kind) 13 | { 14 | } 15 | 16 | public override void Setup(Driver driver) 17 | { 18 | base.Setup(driver); 19 | driver.Options.GenerateDefaultValuesForArguments = true; 20 | driver.Options.GenerateClassTemplates = true; 21 | driver.Options.CompileCode = true; 22 | driver.Options.Modules[1].IncludeDirs.Add(GetTestsDirectory("NamespacesDerived")); 23 | const string @base = "NamespacesBase"; 24 | var module = driver.Options.AddModule(@base); 25 | module.IncludeDirs.Add(Path.GetFullPath(GetTestsDirectory(@base))); 26 | module.Headers.Add($"{@base}.h"); 27 | module.OutputNamespace = @base; 28 | module.LibraryDirs.AddRange(driver.Options.Modules[1].LibraryDirs); 29 | module.Libraries.Add($"{@base}.Native"); 30 | driver.Options.Modules[1].Dependencies.Add(module); 31 | } 32 | 33 | public override void Preprocess(Driver driver, ASTContext ctx) 34 | { 35 | ctx.IgnoreClassWithName("Ignored"); 36 | // operator= for this type isn't necessary for testing 37 | // while also requiring a large amount of C++ to get valid symbols; better ignore 38 | foreach (Method @operator in ctx.FindCompleteClass("StdFields").Operators) 39 | { 40 | @operator.ExplicitlyIgnore(); 41 | } 42 | } 43 | } 44 | 45 | public static class NamespacesDerived 46 | { 47 | public static void Main() 48 | { 49 | ConsoleDriver.Run(new NamespacesDerivedTests(GeneratorKind.CSharp)); 50 | } 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /tests/dotnet/NamespacesDerived/NamespacesDerived.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/NamespacesDerived/NamespacesDerived.Tests.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | ..\..\..\build\gen\NamespacesDerived\NamespacesBase.dll 8 | 9 | 10 | ..\..\..\build\gen\NamespacesDerived\NamespacesDerived.dll 11 | 12 | 13 | -------------------------------------------------------------------------------- /tests/dotnet/NamespacesDerived/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "NamespacesDerived.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/NamespacesDerived/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/Namespaces" 2 | SetupTestNativeProject("NamespacesDerived", "NamespacesBase") 3 | 4 | if not EnabledManagedProjects() then 5 | return 6 | end 7 | 8 | SetupTestGeneratorProject("NamespacesDerived") 9 | SetupTestProjectsCSharp("NamespacesDerived", "NamespacesBase") -------------------------------------------------------------------------------- /tests/dotnet/Native/ASTExtensions.h: -------------------------------------------------------------------------------- 1 | #include "AST.h" 2 | #include 3 | 4 | // Tests class templates across translation units 5 | // Explicit instantiation 6 | template class TestTemplateClass; 7 | // Implicit instantiations 8 | typedef TestTemplateClass TestTemplateClassComplex; 9 | typedef TestTemplateClass> TestTemplateClassMoreComplex; 10 | 11 | template 12 | class ForwardedTemplate 13 | { 14 | }; 15 | -------------------------------------------------------------------------------- /tests/dotnet/Native/Enums.h: -------------------------------------------------------------------------------- 1 | enum 2 | { 3 | UnnamedEnumA1, 4 | EnumUnnamedA2 5 | }; 6 | 7 | // This line will make sure that a visitor won't enumerate all enums across 8 | // different translation units at once. 9 | struct TestUniqueNames 10 | {}; -------------------------------------------------------------------------------- /tests/dotnet/Native/Templates.h: -------------------------------------------------------------------------------- 1 | template 2 | struct integral_constant 3 | { 4 | static constexpr T value = Value; 5 | }; 6 | 7 | template 8 | using bool_constant = integral_constant; 9 | 10 | template 11 | struct is_integral : integral_constant 12 | {}; 13 | 14 | template 15 | struct is_arithmetic : bool_constant::value> 16 | {}; 17 | -------------------------------------------------------------------------------- /tests/dotnet/Native/linux/libexpat.so.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mono/CppSharp/e093f713b90d49528de13afd859e3d1f34cf3049/tests/dotnet/Native/linux/libexpat.so.0 -------------------------------------------------------------------------------- /tests/dotnet/Native/macos/libexpat.dylib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mono/CppSharp/e093f713b90d49528de13afd859e3d1f34cf3049/tests/dotnet/Native/macos/libexpat.dylib -------------------------------------------------------------------------------- /tests/dotnet/Native/windows/libexpat.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mono/CppSharp/e093f713b90d49528de13afd859e3d1f34cf3049/tests/dotnet/Native/windows/libexpat.dll -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "StandardLib.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/StandardLib.Gen.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Generators; 3 | using CppSharp.Utils; 4 | 5 | namespace CppSharp.Tests 6 | { 7 | public class StandardLibTestsGenerator : GeneratorTest 8 | { 9 | public StandardLibTestsGenerator(GeneratorKind kind) 10 | : base("StandardLib", kind) 11 | { 12 | } 13 | 14 | public override void Preprocess(Driver driver, ASTContext ctx) 15 | { 16 | ctx.SetClassAsValueType("IntWrapperValueType"); 17 | } 18 | 19 | public static void Main(string[] args) 20 | { 21 | ConsoleDriver.Run(new StandardLibTestsGenerator(GeneratorKind.CLI)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/StandardLib.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/StandardLib.Tests.CLI.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/StandardLib.Tests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | using StandardLib; 7 | 8 | [TestFixture] 9 | public class StandardLibTests 10 | { 11 | [Test] 12 | public void TestVectors() 13 | { 14 | var vectors = new StandardLib.TestVectors(); 15 | 16 | var sum = vectors.SumIntVector(new List { 1, 2, 3 }); 17 | Assert.AreEqual(sum, 6); 18 | 19 | var list = vectors.IntVector; 20 | Assert.True(list.SequenceEqual(new List { 2, 3, 4 })); 21 | 22 | var ptrList = vectors.IntPtrVector; 23 | var intList = ptrList.Select(ptr => Marshal.ReadInt32(ptr)); 24 | Assert.True(intList.SequenceEqual(new List { 2, 3, 4 })); 25 | 26 | var wrapperList = new List(); 27 | for (int i = 0; i < 3; i++) 28 | wrapperList.Add(new IntWrapper() { Value = i }); 29 | vectors.IntWrapperVector = wrapperList; 30 | wrapperList = vectors.IntWrapperVector; 31 | for (int i = 0; i < 3; i++) 32 | Assert.AreEqual(i, wrapperList[i].Value); 33 | 34 | for (int i = 0; i < 3; i++) 35 | wrapperList[i].Value += i; 36 | 37 | vectors.IntWrapperPtrVector = wrapperList; 38 | wrapperList = vectors.IntWrapperPtrVector; 39 | for (int i = 0; i < 3; i++) 40 | Assert.AreEqual(i * 2, wrapperList[i].Value); 41 | 42 | var valueTypeWrapperList = new List(); 43 | for (int i = 0; i < 3; i++) 44 | valueTypeWrapperList.Add(new IntWrapperValueType() { Value = i }); 45 | vectors.IntWrapperValueTypeVector = valueTypeWrapperList; 46 | valueTypeWrapperList = vectors.IntWrapperValueTypeVector; 47 | for (int i = 0; i < 3; i++) 48 | Assert.AreEqual(i, valueTypeWrapperList[i].Value); 49 | } 50 | 51 | [Test] 52 | public void TestOStream() 53 | { 54 | const string testString = "hello wörld"; 55 | var stringWriter = new StringWriter(); 56 | OStreamTest.WriteToOStream(stringWriter, testString); 57 | Assert.AreEqual(testString, stringWriter.ToString()); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/StandardLib.cpp: -------------------------------------------------------------------------------- 1 | #include "StandardLib.h" 2 | 3 | TestVectors::TestVectors() 4 | { 5 | IntVector.push_back(2); 6 | IntVector.push_back(3); 7 | IntVector.push_back(4); 8 | 9 | IntPtrVector.push_back(&IntVector[0]); 10 | IntPtrVector.push_back(&IntVector[1]); 11 | IntPtrVector.push_back(&IntVector[2]); 12 | } 13 | 14 | std::vector TestVectors::GetIntVector() 15 | { 16 | std::vector vec; 17 | vec.push_back(2); 18 | vec.push_back(3); 19 | vec.push_back(4); 20 | 21 | return vec; 22 | } 23 | 24 | int TestVectors::SumIntVector(std::vector& vec) 25 | { 26 | int sum = 0; 27 | for (unsigned I = 0, E = vec.size(); I != E; ++I) 28 | sum += vec[I]; 29 | 30 | return sum; 31 | } -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/StandardLib.h: -------------------------------------------------------------------------------- 1 | #include "../Tests.h" 2 | #include 3 | #include 4 | 5 | struct DLL_API IntWrapper 6 | { 7 | int Value; 8 | }; 9 | 10 | struct DLL_API IntWrapperValueType 11 | { 12 | int Value; 13 | }; 14 | 15 | typedef std::vector VectorTypedef; 16 | 17 | struct DLL_API TestVectors 18 | { 19 | TestVectors(); 20 | std::vector GetIntVector(); 21 | int SumIntVector(std::vector& vec); 22 | 23 | // Should get mapped to List 24 | std::vector IntVector; 25 | // Should get mapped to List 26 | std::vector IntPtrVector; 27 | // Should get mapped to List 28 | std::vector IntWrapperVector; 29 | // Should get mapped to List 30 | std::vector IntWrapperPtrVector; 31 | // Should get mapped to List 32 | std::vector IntWrapperValueTypeVector; 33 | // Should get mapped to List 34 | VectorTypedef IntWrapperValueTypeVectorTypedef; 35 | }; 36 | 37 | struct DLL_API OStreamTest 38 | { 39 | static void WriteToOStream(std::ostream& stream, const char* s) 40 | { 41 | stream << s; 42 | }; 43 | 44 | static void WriteToOStreamPtr(std::ostream* stream, const char* s) 45 | { 46 | *stream << s; 47 | }; 48 | }; 49 | -------------------------------------------------------------------------------- /tests/dotnet/StandardLib/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/StandardLib" 2 | SetupTestCLI("StandardLib") -------------------------------------------------------------------------------- /tests/dotnet/Test.Bindings.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | true 5 | $(GenDir)$(TestName) 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /tests/dotnet/Test.Common.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | false 5 | false 6 | false 7 | false 8 | false 9 | true 10 | true 11 | true 12 | $(MSBuildProjectName.Substring(0, $(MSBuildProjectName.IndexOf('.')))) 13 | $(TestName).Gen 14 | Exe 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /tests/dotnet/Test.Generator.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | OnOutputUpdated 4 | $(DotNetCmd) "$(OutputPath)$(TestGeneratorName).$(GeneratorFileExtension)" 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /tests/dotnet/Test.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | $(GenDir)$(TestName) 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /tests/dotnet/Tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #if defined(_MSC_VER) 4 | 5 | #if defined(DLL_EXPORT) 6 | #define DLL_API __declspec(dllexport) 7 | #else 8 | #define DLL_API __declspec(dllimport) 9 | #endif 10 | 11 | #ifndef STDCALL 12 | #define STDCALL __stdcall 13 | #endif 14 | 15 | #ifndef CDECL 16 | #define CDECL __cdecl 17 | #endif 18 | 19 | #ifndef THISCALL 20 | #define THISCALL __thiscall 21 | #endif 22 | 23 | // HACK: work around https://developercommunity.visualstudio.com/content/problem/1269158/c4251-shown-for-any-not-explicitly-exported-templa.html 24 | // harmless and requires exporting all template specializations 25 | #pragma warning(disable : 4251) 26 | 27 | #else 28 | #define DLL_API __attribute__((visibility("default"))) 29 | 30 | #ifndef STDCALL 31 | #if defined(WINDOWS) 32 | #define STDCALL __attribute__((stdcall)) 33 | #else 34 | // warning: calling convention 'stdcall' ignored for this target [-Wignored-attributes] 35 | #define STDCALL 36 | #endif 37 | #endif 38 | 39 | #ifndef CDECL 40 | #define CDECL __attribute__((cdecl)) 41 | #endif 42 | 43 | #ifndef THISCALL 44 | #define THISCALL 45 | #endif 46 | 47 | #endif 48 | 49 | #define CS_OUT 50 | #define CS_IN_OUT 51 | #define CS_VALUE_TYPE 52 | -------------------------------------------------------------------------------- /tests/dotnet/VTables/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "VTables.Gen": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /tests/dotnet/VTables/VTables.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/VTables/VTables.Gen.cs: -------------------------------------------------------------------------------- 1 | using CppSharp.AST; 2 | using CppSharp.Generators; 3 | using CppSharp.Passes; 4 | using CppSharp.Utils; 5 | 6 | namespace CppSharp.Tests 7 | { 8 | public class VTableTests : GeneratorTest 9 | { 10 | public VTableTests(GeneratorKind kind) 11 | : base("VTables", kind) 12 | { 13 | } 14 | 15 | public override void Setup(Driver driver) 16 | { 17 | base.Setup(driver); 18 | 19 | driver.ParserOptions.EnableRTTI = true; 20 | } 21 | 22 | public override void SetupPasses(Driver driver) 23 | { 24 | driver.Context.TranslationUnitPasses.AddPass(new FunctionToInstanceMethodPass()); 25 | } 26 | 27 | public override void Preprocess(Driver driver, ASTContext ctx) 28 | { 29 | 30 | } 31 | 32 | public static void Main(string[] args) 33 | { 34 | ConsoleDriver.Run(new VTableTests(GeneratorKind.CLI)); 35 | ConsoleDriver.Run(new VTableTests(GeneratorKind.CSharp)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/dotnet/VTables/VTables.Gen.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/VTables/VTables.Tests.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /tests/dotnet/VTables/VTables.cpp: -------------------------------------------------------------------------------- 1 | #include "VTables.h" 2 | #include 3 | 4 | int Foo::vfoo() 5 | { 6 | return 5; 7 | } 8 | 9 | int Foo::vbar() 10 | { 11 | return vfoo(); 12 | } 13 | 14 | int Foo::append() 15 | { 16 | return 1; 17 | } 18 | 19 | int Foo::append(int a) 20 | { 21 | return ++a; 22 | } 23 | 24 | int Foo::callVirtualWithParameter(int a) 25 | { 26 | return append(a); 27 | } 28 | 29 | int FooCallFoo(Foo* foo) 30 | { 31 | return foo->vfoo() + 2; 32 | } 33 | 34 | int BaseClassVirtual::virtualCallRetInt(BaseClassVirtual* base) 35 | { 36 | return base->retInt(); 37 | } 38 | 39 | int BaseClassVirtual::retInt() 40 | { 41 | return 5; 42 | } 43 | 44 | BaseClassVirtual BaseClassVirtual::getBase() 45 | { 46 | return DerivedClassVirtual(); 47 | } 48 | 49 | BaseClassVirtual* BaseClassVirtual::getBasePtr() 50 | { 51 | return new DerivedClassVirtual(); 52 | } 53 | 54 | const char* BaseClassVirtual::getTypeName() 55 | { 56 | return typeid(BaseClassVirtual).name(); 57 | } 58 | 59 | int DerivedClassVirtual::retInt() 60 | { 61 | return 10; 62 | } 63 | -------------------------------------------------------------------------------- /tests/dotnet/VTables/VTables.h: -------------------------------------------------------------------------------- 1 | #include "../Tests.h" 2 | #include 3 | 4 | class DLL_API Foo 5 | { 6 | public: 7 | class Vfoo 8 | { 9 | }; 10 | 11 | virtual int vfoo(); 12 | virtual int vbar(); 13 | 14 | virtual int append(); 15 | virtual int append(int a); 16 | int callVirtualWithParameter(int a); 17 | std::string s; 18 | }; 19 | 20 | DLL_API int FooCallFoo(Foo* foo); 21 | 22 | class DLL_API BaseClassVirtual 23 | { 24 | public: 25 | static int virtualCallRetInt(BaseClassVirtual* base); 26 | virtual int retInt(); 27 | static BaseClassVirtual getBase(); 28 | static BaseClassVirtual* getBasePtr(); 29 | static const char* getTypeName(); 30 | }; 31 | 32 | class DLL_API DerivedClassVirtual : public BaseClassVirtual 33 | { 34 | public: 35 | virtual int retInt() override; 36 | }; 37 | -------------------------------------------------------------------------------- /tests/dotnet/VTables/premake4.lua: -------------------------------------------------------------------------------- 1 | group "Tests/VTables" 2 | SetupTestCSharp("VTables") 3 | 4 | if EnableNativeProjects() then 5 | 6 | project("VTables.Native") 7 | rtti "On" 8 | 9 | end 10 | -------------------------------------------------------------------------------- /tests/emscripten/.gitignore: -------------------------------------------------------------------------------- 1 | gen 2 | *.so 3 | *.dylib 4 | *.dll 5 | -------------------------------------------------------------------------------- /tests/emscripten/bindings.lua: -------------------------------------------------------------------------------- 1 | generator "emscripten" 2 | platform "emscripten" 3 | architecture "wasm32" 4 | 5 | includedirs 6 | { 7 | "..", 8 | "../../include", 9 | } 10 | 11 | output "gen" 12 | 13 | module "tests" 14 | namespace "test" 15 | headers 16 | { 17 | "Builtins.h", 18 | "Classes.h", 19 | "Classes2.h", 20 | "Delegates.h", 21 | "Enums.h", 22 | "Overloads.h" 23 | } 24 | -------------------------------------------------------------------------------- /tests/emscripten/premake5.lua: -------------------------------------------------------------------------------- 1 | 2 | workspace "emscripten" 3 | configurations { "debug", "release" } 4 | location "gen" 5 | symbols "On" 6 | optimize "Off" 7 | cppdialect "C++14" 8 | 9 | project "test" 10 | kind "SharedLib" 11 | language "C++" 12 | files 13 | { 14 | "gen/**.cpp", 15 | } 16 | includedirs 17 | { 18 | "..", 19 | "../../include" 20 | } 21 | linkoptions { "--bind -sENVIRONMENT=node -sMODULARIZE=1 -sEXPORT_ALL -sEXPORT_ES6=1 -sUSE_ES6_IMPORT_META=1" } 22 | targetextension ".mjs" -------------------------------------------------------------------------------- /tests/emscripten/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | dir=$(cd "$(dirname "$0")"; pwd) 5 | rootdir="$dir/../.." 6 | dotnet_configuration=DebugOpt 7 | make_configuration=debug 8 | platform=x64 9 | jsinterp=$(which node) 10 | 11 | usage() { 12 | cat <&2 41 | usage 42 | ;; 43 | esac 44 | done 45 | 46 | if [ "$CI" = "true" ]; then 47 | red="" 48 | green="" 49 | reset="" 50 | else 51 | red=`tput setaf 1` 52 | green=`tput setaf 2` 53 | reset=`tput sgr0` 54 | fi 55 | 56 | # 1) Generate 57 | generate=true 58 | if [ $generate = true ]; then 59 | echo "${green}Generating bindings with .NET configuration $dotnet_configuration${reset}" 60 | dotnet "$rootdir/bin/${dotnet_configuration}/CppSharp.CLI.dll" --property=keywords \ 61 | "$dir/bindings.lua" 62 | fi 63 | 64 | # 2) Build 65 | echo "${green}Building generated binding files (make config: $make_configuration)${reset}" 66 | premake="$rootdir/build/premake.sh" 67 | "$premake" --file=$dir/premake5.lua gmake2 68 | config=$make_configuration emmake make -C "$dir/gen" 69 | 70 | # 3) Test 71 | echo 72 | echo "${green}Executing JS tests with Node${reset}" 73 | "$jsinterp" "$dir/test.mjs" 74 | -------------------------------------------------------------------------------- /tests/emscripten/utils.mjs: -------------------------------------------------------------------------------- 1 | export function assert(actual, expected, message) { 2 | if (arguments.length == 1) 3 | expected = true; 4 | 5 | if (actual === expected) 6 | return; 7 | 8 | if (actual !== null && expected !== null 9 | && typeof actual == 'object' && typeof expected == 'object' 10 | && actual.toString() === expected.toString()) 11 | return; 12 | 13 | throw Error("assertion failed: got |" + actual + "|" + 14 | ", expected |" + expected + "|" + 15 | (message ? " (" + message + ")" : "")); 16 | } 17 | 18 | export const eq = assert; 19 | export const floateq = (actual, expected) => { assert(Math.abs(actual - expected) < 0.01) } 20 | 21 | export const ascii = v => v.charCodeAt(0) 22 | -------------------------------------------------------------------------------- /tests/napi/.gitignore: -------------------------------------------------------------------------------- 1 | gen 2 | -------------------------------------------------------------------------------- /tests/napi/premake5.lua: -------------------------------------------------------------------------------- 1 | workspace "test" 2 | configurations {"Debug", "Release"} 3 | location "gen" 4 | symbols "On" 5 | optimize "Off" 6 | project "tests" 7 | kind "SharedLib" 8 | files {"gen/**.cpp"} 9 | includedirs {".."} 10 | targetprefix "" 11 | targetextension ".node" 12 | -------------------------------------------------------------------------------- /tests/napi/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | dir=$(cd "$(dirname "$0")"; pwd) 5 | rootdir="$dir/../.." 6 | dotnet_configuration=DebugOpt 7 | make_configuration=debug 8 | platform=x64 9 | jsinterp=$(which node) 10 | 11 | usage() { 12 | cat <&2 41 | usage 42 | ;; 43 | esac 44 | done 45 | 46 | if [ "$CI" = "true" ]; then 47 | red="" 48 | green="" 49 | reset="" 50 | else 51 | red=`tput setaf 1` 52 | green=`tput setaf 2` 53 | reset=`tput sgr0` 54 | fi 55 | 56 | # 1) Generate 57 | generate=true 58 | if [ $generate = true ]; then 59 | echo "${green}Generating bindings with .NET configuration $dotnet_configuration${reset}" 60 | dotnet "$rootdir/bin/${dotnet_configuration}/CppSharp.CLI.dll" \ 61 | --gen=napi -I$dir/.. -o $dir/gen -m tests $dir/../*.h 62 | fi 63 | 64 | # 2) Build 65 | echo "${green}Building generated binding files (make config: $make_configuration)${reset}" 66 | premake="$rootdir/build/premake.sh" 67 | "$premake" --file=$dir/premake5.lua gmake 68 | config=$make_configuration make -C "$dir/gen" 69 | 70 | # 3) Test 71 | echo 72 | echo "${green}Executing JS tests with Node${reset}" 73 | "$jsinterp" "$dir/test.js" 74 | -------------------------------------------------------------------------------- /tests/quickjs/.gitignore: -------------------------------------------------------------------------------- 1 | runtime/ 2 | gen/ 3 | *.so 4 | *.dylib 5 | *.dll 6 | -------------------------------------------------------------------------------- /tests/quickjs/bindings.lua: -------------------------------------------------------------------------------- 1 | generator "quickjs" 2 | architecture "x64" 3 | 4 | includedirs 5 | { 6 | "..", 7 | "../../include", 8 | } 9 | 10 | output "gen" 11 | 12 | module "test" 13 | namespace "test" 14 | headers 15 | { 16 | "Builtins.h", 17 | "Classes.h", 18 | "Classes2.h", 19 | "Delegates.h", 20 | "Enums.h", 21 | "Overloads.h" 22 | } 23 | -------------------------------------------------------------------------------- /tests/quickjs/bootstrap.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | dir=$(cd "$(dirname "$0")"; pwd) 4 | rootdir="$dir/../.." 5 | 6 | cd $dir 7 | 8 | if [ ! -d runtime ]; then 9 | git clone https://github.com/quickjs-ng/quickjs.git runtime 10 | git -C runtime reset --hard 0e5e9c2c49db15ab9579edeb4d90e610c8b8463f 11 | fi 12 | 13 | if [ ! -f runtime/build/qjs ]; then 14 | make -C runtime/ 15 | fi 16 | -------------------------------------------------------------------------------- /tests/quickjs/premake5.lua: -------------------------------------------------------------------------------- 1 | local cppsharp_qjs_runtime = "../../src/Generator/Generators/QuickJS/Runtime" 2 | 3 | workspace "qjs" 4 | configurations { "debug", "release" } 5 | location "gen" 6 | symbols "On" 7 | optimize "Off" 8 | 9 | project "test" 10 | kind "SharedLib" 11 | language "C++" 12 | cppdialect "C++11" 13 | files 14 | { 15 | "gen/**.cpp", 16 | cppsharp_qjs_runtime .. "/*.cpp", 17 | cppsharp_qjs_runtime .. "/*.c" 18 | } 19 | includedirs 20 | { 21 | "runtime", 22 | cppsharp_qjs_runtime, 23 | "..", 24 | "../../include" 25 | } 26 | libdirs { qjs_lib_dir } 27 | filter { "kind:StaticLib" } 28 | links { "quickjs" } 29 | filter { "kind:SharedLib" } 30 | defines { "JS_SHARED_LIBRARY" } 31 | filter { "kind:SharedLib", "system:macosx" } 32 | linkoptions { "-undefined dynamic_lookup" } 33 | targetextension (".so") 34 | -------------------------------------------------------------------------------- /tests/quickjs/test-prop.js: -------------------------------------------------------------------------------- 1 | class A 2 | { 3 | get foo() { return 1; } 4 | } 5 | 6 | class B extends A 7 | { 8 | 9 | } 10 | 11 | let a = new A(); 12 | console.log(a.foo) 13 | 14 | let b = new B(); 15 | console.log(b.foo) 16 | -------------------------------------------------------------------------------- /tests/quickjs/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | dir=$(cd "$(dirname "$0")"; pwd) 5 | rootdir="$dir/../.." 6 | dotnet_configuration=DebugOpt 7 | make_configuration=debug 8 | platform=x64 9 | jsinterp="$dir/runtime/build/qjs" 10 | 11 | usage() { 12 | cat <&2 41 | usage 42 | ;; 43 | esac 44 | done 45 | 46 | if [ "$CI" = "true" ]; then 47 | red="" 48 | green="" 49 | reset="" 50 | else 51 | red=`tput setaf 1` 52 | green=`tput setaf 2` 53 | reset=`tput sgr0` 54 | fi 55 | 56 | # 1) Generate 57 | generate=true 58 | if [ $generate = true ]; then 59 | echo "${green}Generating bindings with .NET configuration $dotnet_configuration${reset}" 60 | dotnet "$rootdir/bin/${dotnet_configuration}/CppSharp.CLI.dll" "$dir/bindings.lua" 61 | fi 62 | 63 | # 2) Build 64 | echo "${green}Building generated binding files (make config: $make_configuration)${reset}" 65 | premake="$rootdir/build/premake.sh" 66 | "$premake" --file=$dir/premake5.lua gmake2 67 | config=$make_configuration verbose=true make -C "$dir/gen" 68 | 69 | # 3) Test 70 | echo 71 | echo "${green}Executing JS tests with QuickJS${reset}" 72 | cp $dir/gen/bin/$make_configuration/libtest.so $dir 73 | $jsinterp --std $dir/test.js 74 | -------------------------------------------------------------------------------- /tests/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | dir=$(cd "$(dirname "$0")"; pwd) 4 | 5 | # $dir/napi/test.sh 6 | $dir/quickjs/test.sh 7 | $dir/emscripten/test.sh 8 | -------------------------------------------------------------------------------- /tests/ts/.gitignore: -------------------------------------------------------------------------------- 1 | gen 2 | *.js 3 | *.map 4 | -------------------------------------------------------------------------------- /tests/ts/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | dir=$(cd "$(dirname "$0")"; pwd) 5 | rootdir="$dir/../.." 6 | dotnet_configuration=DebugOpt 7 | make_configuration=debug 8 | platform=x64 9 | jsinterp="$dir/runtime/build/qjs" 10 | 11 | usage() { 12 | cat <&2 41 | usage 42 | ;; 43 | esac 44 | done 45 | 46 | if [ "$CI" = "true" ]; then 47 | red="" 48 | green="" 49 | reset="" 50 | else 51 | red=`tput setaf 1` 52 | green=`tput setaf 2` 53 | reset=`tput sgr0` 54 | fi 55 | 56 | # 1) Generate 57 | generate=true 58 | if [ $generate = true ]; then 59 | echo "${green}Generating bindings with .NET configuration $dotnet_configuration${reset}" 60 | dotnet "$rootdir/bin/${dotnet_configuration}/CppSharp.CLI.dll" \ 61 | --gen=ts -I$dir/.. -I$rootdir/include -o $dir/gen -m tests $dir/../*.h 62 | fi 63 | 64 | # 2) Type-checking 65 | echo "${green}Typechecking generated binding files with tsc${reset}" 66 | #tsc --noEmit --strict --noImplicitAny --strictNullChecks --strictFunctionTypes --noImplicitThis gen/*.d.ts 67 | -------------------------------------------------------------------------------- /tests/ts/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["*.ts", "./gen/*.ts"], 3 | "compilerOptions": { 4 | "alwaysStrict": true, // Parse in strict mode and emit "use strict" for each source file. 5 | "noImplicitAny": true, 6 | "strictNullChecks": true, 7 | "sourceMap": true, 8 | "typeRoots": ["./gen"] 9 | }, 10 | "typeAcquisition": { 11 | "include": ["gen"] 12 | } 13 | } -------------------------------------------------------------------------------- /version.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", 3 | "version": "1.1", 4 | "publicReleaseRefSpec": [ 5 | "^refs/heads/master$", 6 | "^refs/tags/v\\d\\.\\d" 7 | ] 8 | } 9 | --------------------------------------------------------------------------------