Git Product home page Git Product logo

clangsharp's Introduction

ClangSharp

ClangSharp provides Clang bindings written in C#. It is self-hosted and auto-generates itself by parsing the Clang C header files using ClangSharpPInvokeGenerator.

ci

A nuget package for the project is provided here: https://www.nuget.org/packages/clangsharp. A .NET tool for the P/Invoke generator project is provided here: https://www.nuget.org/packages/ClangSharpPInvokeGenerator

NOTE: If you are running as a dotnet tool, you may need to manually copy the appropriate DLLs from NuGet due to limitations in the dotnet tool support.

A convenience package which provides the native libClang library for several platforms is provided here: https://www.nuget.org/packages/libclang

A helper package which exposes many Clang APIs missing from libClang is provided here: https://www.nuget.org/packages/libClangSharp

NOTE: libclang and libClangSharp are meta-packages which point to the platform-specific runtime packages (e.g.; see others owned by tannergooding). Several manual steps may be required to use them, see discussion in #46 and #118.

Nightly packages are available via the NuGet Feed URL: https://pkgs.clangsharp.dev/index.json

Source browsing is available via: https://source.clangsharp.dev/

Table of Contents

Code of Conduct

ClangSharp and everyone contributing (this includes issues, pull requests, the wiki, etc) must abide by the .NET Foundation Code of Conduct: https://dotnetfoundation.org/about/code-of-conduct.

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected].

License

Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See LICENSE.md in the repository root for more information.

Features

  • Auto-generated using Clang C headers files, and supports all functionality exposed by them ~ which means you can build tooling around C/C++
  • Exposes the raw unsafe API for performance
  • Exposes a slightly higher abstraction that is type safe (CXIndex and CXTranslationUnit are different types, despite being pointers internally)
  • Exposes an again slightly higher abstraction that tries to mirror the Clang C++ Type Hierarchy where possible
  • Nearly identical to the Clang C APIs, e.g. clang_getDiagnosticSpelling in C, vs. clang.getDiagnosticSpelling (notice the . in the C# API)

Building Managed

ClangSharp requires the .NET 8 SDK and can be built simply with dotnet build -c Release.

You can reproduce what the CI environment does by running ./scripts/cibuild.cmd on Windows or ./scripts.cibuild.sh on Unix. This will download the required .NET SDK locally and use that to build the repo; it will also run through all available actions in the appropriate order.

There are also several build scripts in the repository root. On Windows these scripts end with .cmd and expect arguments with a - prefix. On Unix these scripts end with .sh and expect arguments with a -- prefix. By default, each script performs only the action specified in its name (i.e. restore only restores, build only builds, test only tests, and pack only packs). You can specify additional actions to be run by passing that name as an argument to the script (e.g. build.cmd -restore will perform a package restore and build; test.cmd -pack will run tests and package artifacts). Certain actions are dependent on a previous action having been run at least once. build depends on restore, test depends on build, and pack depends on build. This means the recommended first time action is build -restore.

You can see any additional options that are available by passing -help on Windows or --help on Unix to the available build scripts.

Building Native

ClangSharp provides a helper library, libClangSharp, that exposes additional functionality that is not available in libClang. Building this requires CMake 3.13 or later as well as a version of MSVC or Clang that supports C++ 17.

To successfully build libClangSharp you must first build Clang (https://clang.llvm.org/get_started.html).

Windows

The process done on Windows is roughly:

git clone --single-branch --branch llvmorg-18.1.3 https://github.com/llvm/llvm-project
cd llvm-project
mkdir artifacts/bin
cd artifacts/bin
cmake -DCMAKE_INSTALL_PREFIX=../install -DLLVM_ENABLE_PROJECTS=clang -G "Visual Studio 17 2022" -A x64 -Thost=x64 ../../llvm

You can then open LLVM.sln in Visual Studio, change the configuration to Release and build the install project.

Afterwards, you can then build libClangSharp where the process followed is roughly:

git clone https://github.com/dotnet/clangsharp
cd clangsharp
mkdir artifacts/bin/native
cd artifacts/bin/native
cmake -DCMAKE_INSTALL_PREFIX=../install -DPATH_TO_LLVM=../../../../llvm-project/artifacts/install -G "Visual Studio 17 2022" -A x64 -Thost=x64 ../../..

You can then open libClangSharp.sln in Visual Studio, change the configuration to Release and build the install project.

Linux

The process done on Linux is roughly:

git clone --single-branch --branch llvmorg-18.1.3 https://github.com/llvm/llvm-project
cd llvm-project
mkdir -p artifacts/bin
cd artifacts/bin
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../install -DLLVM_ENABLE_PROJECTS=clang ../../llvm
make install

If you want your Linux build to be portable, you may also consider specifying the following options:

  • -DLLVM_ENABLE_TERMINFO=OFF
  • -DLLVM_ENABLE_ZLIB=OFF
  • -DLLVM_ENABLE_ZSTD=OFF
  • -DLLVM_STATIC_LINK_CXX_STDLIB=ON

If you would prefer to use Ninja, then make sure to pass in -G Ninja and then invoke ninja rather than make install.

Afterwards, you can then build libClangSharp where the process followed is roughly:

git clone https://github.com/dotnet/clangsharp
cd clangsharp
mkdir -p artifacts/bin/native
cd artifacts/bin/native
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../install -DPATH_TO_LLVM=../../../../llvm-project/artifacts/install ../../../
make install

Generating Bindings

This program will take a given set of C or C++ header files and generate C# bindings from them. It is still a work-in-progress and not every declaration can have bindings generated today (contributions are welcome).

The simplest and recommended setup is to install the generator as a .NET tool and then use response files:

dotnet tool install --global ClangSharpPInvokeGenerator --version 18.1.0
ClangSharpPInvokeGenerator @generate.rsp

A response file allows you to specify and checkin the command line arguments in a text file, with one argument per line. For example: https://github.com/dotnet/ClangSharp/blob/main/sources/ClangSharpPInvokeGenerator/Properties/GenerateClang.rsp At a minimum, the command line expects one or more input files (-f), an output namespace (-n), and an output location (-o). A typical response file may also specify explicit files to traverse, configuration options, name remappings, and other fixups.

The full set of available switches:

ClangSharpPInvokeGenerator
  ClangSharp P/Invoke Binding Generator

Usage:
  ClangSharpPInvokeGenerator [options]

Options:
  -a, --additional <additional>                                    An argument to pass to Clang when parsing the input files. []
  -c, --config <config>                                            A configuration option that controls how the bindings are generated. Specify 'help' to see the available options. []
  -D, --define-macro <define-macro>                                Define <macro> to <value> (or 1 if <value> omitted). []
  -e, --exclude <exclude>                                          A declaration name to exclude from binding generation. []
  -f, --file <file>                                                A file to parse and generate bindings for. []
  -F, --file-directory <file-directory>                            The base path for files to parse. []
  -h, --headerFile <headerFile>                                    A file which contains the header to prefix every generated file with. []
  -i, --include <include>                                          A declaration name to include in binding generation. []
  -I, --include-directory <include-directory>                      Add directory to include search path. []
  -x, --language <language>                                        Treat subsequent input files as having type <language>. [default: c++]
  -l, --libraryPath <libraryPath>                                  The string to use in the DllImport attribute used when generating bindings. []
  -m, --methodClassName <methodClassName>                          The name of the static class that will contain the generated method bindings. [default: Methods]
  -n, --namespace <namespace>                                      The namespace in which to place the generated bindings. []
  --nativeTypeNamesToStrip                                         The contents to strip from the generated NativeTypeName attributes.
  -om, --output-mode <CSharp|Xml>                                  The mode describing how the information collected from the headers are presented in the resultant bindings. [default: CSharp]
  -o,  --output <output>                                            The output location to write the generated bindings to. []
  -p, --prefixStrip <prefixStrip>                                  The prefix to strip from the generated method bindings. []
  -r, --remap <remap>                                              A declaration name to be remapped to another name during binding generation. []
  -std, --std <std>                                                Language standard to compile for. []
  -to, --test-output <test-output>                                 The output location to write the generated tests to. []
  -t, --traverse <traverse>                                        A file name included either directly or indirectly by -f that should be traversed during binding generation. []
  -v, --version <version>                                          Prints the current version information for the tool and its native dependencies.
  -was, --with-access-specifier <with-access-specifier>            An access specifier to be used with the given qualified or remapped declaration name during binding generation. Supports wildcards. []
  -wa, --with-attribute <with-attribute>                           An attribute to be added to the given remapped declaration name during binding generation. Supports wildcards. []
  -wcc, --with-callconv <with-callconv>                            A calling convention to be used for the given declaration during binding generation. Supports wildcards. []
  -wc, --with-class <with-class>                                   A class to be used for the given remapped constant or function declaration name during binding generation. Supports wildcards. []
  -wg, --with-guid <with-guid>                                     A GUID to be used for the given declaration during binding generation. Supports wildcards. []
  -wlb, --with-librarypath <with-librarypath>                      A library path to be used for the given declaration during binding generation. Supports wildcards. []
  -wmi, --with-manual-import <with-manual-import>                  A remapped function name to be treated as a manual import during binding generation. Supports wildcards. []
  -wn, --with-namespace <with-namespace>                           A namespace to be used for the given remapped declaration name during binding generation. Supports wildcards. []
  -wp, --with-packing <with-packing>                               Overrides the StructLayoutAttribute.Pack property for the given type. Supports wildcards. []
  -wsle, --with-setlasterror <with-setlasterror>                   Add the SetLastError=true modifier to a given DllImport or UnmanagedFunctionPointer. Supports wildcards. []
  -wsgct, --with-suppressgctransition <with-suppressgctransition>  Add the SuppressGCTransition calling convention to a given DllImport or UnmanagedFunctionPointer. Supports wildcards. []
  -wts, --with-transparent-struct <with-transparent-struct>        A remapped type name to be treated as a transparent wrapper during binding generation. Supports wildcards. []
  -wt, --with-type <with-type>                                     A type to be used for the given enum declaration during binding generation. Supports wildcards. []
  -wu, --with-using <with-using>                                   A using directive to be included for the given remapped declaration name during binding generation. Supports wildcards. []
  -?, -h, --help                                                   Show help and usage information

Wildcards:
You can use * as catch-all rule for remapping procedures. For example if you want make all of your generated code internal you can use --with-access-specifier *=Internal.

The available configuration options (visible with -c help) are:

--config, -c    A configuration option that controls how the bindings are generated. Specify 'help' to see the available options.

Options:
  ?, h, help                             Show help and usage information for -c, --config

  # Codegen Options

  compatible-codegen                     Bindings should be generated with .NET Standard 2.0 compatibility. Setting this disables preview code generation.
  default-codegen                        Bindings should be generated for the previous LTS version of .NET/C#. This is currently .NET 6/C# 10.
  latest-codegen                         Bindings should be generated for the current LTS/STS version of .NET/C#. This is currently .NET 8/C# 12.
  preview-codegen                        Bindings should be generated for the preview version of .NET/C#. This is currently .NET 9/C# 13.

  # File Options

  single-file                            Bindings should be generated to a single output file. This is the default.
  multi-file                             Bindings should be generated so there is approximately one type per file.

  # Type Options

  unix-types                             Bindings should be generated assuming Unix defaults. This is the default on Unix platforms.
  windows-types                          Bindings should be generated assuming Windows defaults. This is the default on Windows platforms.

  # Exclusion Options

  exclude-anonymous-field-helpers        The helper ref properties generated for fields in nested anonymous structs and unions should not be generated.
  exclude-com-proxies                    Types recognized as COM proxies should not have bindings generated. Thes are currently function declarations ending with _UserFree, _UserMarshal, _UserSize, _UserUnmarshal, _Proxy, or _Stub.
  exclude-default-remappings             Default remappings for well known types should not be added. This currently includes intptr_t, ptrdiff_t, size_t, and uintptr_t
  exclude-empty-records                  Bindings for records that contain no members should not be generated. These are commonly encountered for opaque handle like types such as HWND.
  exclude-enum-operators                 Bindings for operators over enum types should not be generated. These are largely unnecessary in C# as the operators are available by default.
  exclude-fnptr-codegen                  Generated bindings for latest or preview codegen should not use function pointers.
  exclude-funcs-with-body                Bindings for functions with bodies should not be generated.
  exclude-using-statics-for-enums        Enum usages should be fully qualified and should not include a corresponding 'using static EnumName;'

  # Vtbl Options

  explicit-vtbls                         VTBLs should have an explicit type generated with named fields per entry.
  implicit-vtbls                         VTBLs should be implicit to reduce metadata bloat. This is the current default
  trimmable-vtbls                        VTBLs should be defined but not used in helper methods to reduce metadata bloat when trimming.

  # Test Options

  generate-tests-nunit                   Basic tests validating size, blittability, and associated metadata should be generated for NUnit.
  generate-tests-xunit                   Basic tests validating size, blittability, and associated metadata should be generated for XUnit.

  # Generation Options

  generate-aggressive-inlining           [MethodImpl(MethodImplOptions.AggressiveInlining)] should be added to generated helper functions.
  generate-callconv-member-function      Instance function pointers should use [CallConvMemberFunction] where applicable.
  generate-cpp-attributes                [CppAttributeList("")] should be generated to document the encountered C++ attributes.
  generate-disable-runtime-marshalling   [assembly: DisableRuntimeMarshalling] should be generated.
  generate-doc-includes                  &lt;include&gt; xml documentation tags should be generated for declarations.
  generate-file-scoped-namespaces        Namespaces should be scoped to the file to reduce nesting.
  generate-guid-member                   Types with an associated GUID should have a corresponding member generated.
  generate-helper-types                  Code files should be generated for various helper attributes and declared transparent structs.
  generate-macro-bindings                Bindings for macro-definitions should be generated. This currently only works with value like macros and not function-like ones.
  generate-marker-interfaces             Bindings for marker interfaces representing native inheritance hierarchies should be generated.
  generate-native-bitfield-attribute     [NativeBitfield(\"\", offset: #, length: #)] attribute should be generated to document the encountered bitfield layout.
  generate-native-inheritance-attribute  [NativeInheritance("")] attribute should be generated to document the encountered C++ base type.
  generate-setslastsystemerror-attribute [SetsLastSystemError] attribute should be generated rather than using SetLastError = true.
  generate-template-bindings             Bindings for template-definitions should be generated. This is currently experimental.
  generate-unmanaged-constants           Unmanaged constants should be generated using static ref readonly properties. This is currently experimental.
  generate-vtbl-index-attribute          [VtblIndex(#)] attribute should be generated to document the underlying VTBL index for a helper method.

  # Stripping Options

  strip-enum-member-type-name            Strips the enum type name from the beginning of its member names.

  # Logging Options

  log-exclusions                         A list of excluded declaration types should be generated. This will also log if the exclusion was due to an exact or partial match.
  log-potential-typedef-remappings       A list of potential typedef remappings should be generated. This can help identify missing remappings.
  log-visited-files                      A list of the visited files should be generated. This can help identify traversal issues.

Using locally built versions

After you build local version, you can use executable from build location.

artifacts/bin/sources/ClangSharpPInvokeGenerator/Debug/net6.0/ClangSharpPInvokeGenerator

If you are on Linux

LD_LIBRARY_PATH=$(pwd)/artifacts/bin/native/lib/
artifacts/bin/sources/ClangSharpPInvokeGenerator/Debug/net6.0/ClangSharpPInvokeGenerator

Spotlight

The P/Invoke Generator is currently used by several projects:

clangsharp's People

Contributors

amaitland avatar andrew-boyarshin avatar benpye avatar berrysoft avatar ceresgalax avatar dazombiekiller avatar dpaoliello avatar finitereality avatar fredrikhr avatar gasinfinity avatar kant2002 avatar kkukshtel avatar mixaill avatar mjsabby avatar objectx avatar pathogendavid avatar reflectronic avatar saucecontrol avatar seeminglyscience avatar solalpirelli avatar sotteson1 avatar stanionascu avatar summpot avatar tannergooding avatar techpizzadev avatar teo-tsirpanis avatar thadhouse avatar theleftexit avatar udaken avatar zeule avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clangsharp's Issues

Runtime packages not restoring properly?

I'm trying to use ClangSharp v9.0.0 beta from NuGet and i had a lot of trouble getting the libClang and libClangSharp native dependencies to load. I had to manually add the win-x64 runtime packages in order to have them deployed to the runtimes directory to be loaded.

Are we supposed to do this manually, or is NuGet supposed to automatically add the dependencies based on the main dependency specified in the libClang and libClangSharp packages? I'm not knowledgeable enough on NuGet to know what it can do so i'm at a loss here.

Explicitly set C# version

After cloning the repo and opening it in Visual Studio 2017, IntelliSense complains about missing language features. This is since by default the last major version of C# is used (7.0) and certain features are 7.1+ (such as async Main). I suggest setting the LangVersion in the csproj files to latest:

<LangVersion>latest</LangVersion>

Setup a CI system for ClangSharp

As per #34 (comment), it would be nice if ClangSharp could be connected to Azure DevOps for CI and other build infrastructure niceties.

It may be possible to utilize dotnet/arcade for this, or to setup a smaller localized infrastructure.

Update to Clang v9.0.0

Clang v9.0.0 was just released and both libClang and the bindings should be updated to use it.

Multiple issues with ClangSharp

I'm looking to replace my SWIG generated and ManagedCuda wrappers for CUDA with a ClangSharp-generated wrapper (SWIG rules are just to arcane). ClangSharpPInvokeGenerator looks promising, but there are several issues:

  1. ClangSharp seems to be in two locations: https://github.com/Microsoft/ClangSharp and as a sub project in LLVM https://github.com/Microsoft/LLVMSharp/tree/master/tools/ClangSharpPInvokeGenerator
    Which is it? I assume https://github.com/Microsoft/ClangSharp is the correct source as it was more recently updated.

  2. In cuda.h, there are many typedef declarations, for example:

typedef enum CUaddress_mode_enum { CU_TR_ADDRESS_MODE_WRAP = 0, /**< Wrapping address mode */ CU_TR_ADDRESS_MODE_CLAMP = 1, /**< Clamp to edge address mode */ CU_TR_ADDRESS_MODE_MIRROR = 2, /**< Mirror address mode */ CU_TR_ADDRESS_MODE_BORDER = 3 /**< Border address mode */ } CUaddress_mode;

The generator handles the enum, but not the typedef. A "using ... = ..." might be appropriate.

  1. The generator does not handle C unions, nor anonymous types well. In cuda.h, there is the following decl:

union { struct { CUarray hArray; /**< CUDA array */ } array; struct { CUmipmappedArray hMipmappedArray; /**< CUDA mipmapped array */ } mipmap; struct { CUdeviceptr devPtr; /**< Device pointer */ CUarray_format format; /**< Array format */ unsigned int numChannels; /**< Channels per array element */ size_t sizeInBytes; /**< Size in bytes */ } linear; struct { CUdeviceptr devPtr; /**< Device pointer */ CUarray_format format; /**< Array format */ unsigned int numChannels; /**< Channels per array element */ size_t width; /**< Width of the array in elements */ size_t height; /**< Height of the array in elements */ size_t pitchInBytes; /**< Pitch between two rows in bytes */ } pitch2D; struct { int reserved[32]; } reserved; } res;

The generator bypasses unions completely. For anonymous structs (e.g., contained in the above union), the generator assigns the name "" as the anonymous type name, but it should make it unique, eg "" + int_id++, because after creating the type, it tests to see if the type was declared previously, and thinks that it was already declared.

I'm planning on a patch for ClangSharp to fix these problems in the next couple days as I'd like to get the tool to work with CUDA asap so I can get back to work on my C#/CIL compiler for GPUs.

Ken Domino

Binary operator overloads missing required parentheses

From winnt.h:

public static JOB_OBJECT_NET_RATE_CONTROL_FLAGS Or(JOB_OBJECT_NET_RATE_CONTROL_FLAGS a, JOB_OBJECT_NET_RATE_CONTROL_FLAGS b)
{
    return (JOB_OBJECT_NET_RATE_CONTROL_FLAGS)((int)a) | ((int)b);
}

This is causing the following compiler error due to missing parentheses around the binary operator and its operands:

CS0019	Operator '|' cannot be applied to operands of type 'JOB_OBJECT_NET_RATE_CONTROL_FLAGS' and 'int'

www.clangsharp.org reports Azure 404

Seems that going to clangsharp.org has some configuration problem in Azure.

Is this project still active?

================ Text from clangsharp.org ===============

Error 404 - Web app not found.

The web app you have attempted to reach is not available in this Microsoft Azure App Service region. This could be due to one of several reasons:

  1. The web app owner has registered a custom domain to point to the Microsoft Azure App Service, but has not yet configured Azure to recognize it. Click here to read more.

  2. The web app owner has moved the web app to a different region, but the DNS cache is still directing to the old IP Address that was used in the previous region. Click here to read more.

-include parameter does not seem to work

I am using -include as command line parameter to get some type definitions that are presupposed by a header file that I need to parse and analyse. This works fine when I call clang directly from the command shell, but seems to fail when I call parseTranslationUnit2() via CLangSharp.

I have attached a little demo application where datatypes.h has the typedef u8 which is implicitly required from DataDictionary.h, the file that should be analysed. In the example all u8 based type declarations are resolved to int, so I suppose that the -include command line option is somehow not working.

Any ideas about this?
ConsoleApp1.zip

Cannot use on OS X

Hi,

After installing ClangSharp from the nuget package managaer using Visual Studio for Mac, the program throws errors.

/Users/richardbamford/.nuget/packages/clangsharp/3.8.0/build/ClangSharp.targets(5,5): Error: ClangSharp requires the platform target for the solution and/or project to be either x86 or x64 to PInvoke appropriately. (rr)

Any idea how to fix this?

libclang alternative names

On at least Ubuntu the dynamic library is called libclang-x.x.so rather than just libclang.so, this means a symlink currently needs to be created so that the DllImport may find the shared library. Ideally there would be some other solution for this, this matters more for .NET Core where there is no concept of a DllMap as on Mono. Maybe dotnet/corefx#27258 and the corresponding CoreCLR work may provide a solution in .NET Core 2.2 or above, however perhaps some other solution could be found before then.

Clarify clang version/building instructions

Hey,

It's difficult from the codebase to know which Clang version is currently bound to the generated codegen.

I assume that the current version is 8.0.0? (as per PR #28)

Could we add this information to the readme.md? (along some prerequisites - what to install to get ClangSharp generator working...etc)

If you are ok with that, I can send a PR?

Side question: how do you see the packaging automated (even locally)? Do we want to put the relevant libclang DLLs for all platforms in an ext in LFS on github and grab them automatically in the runtime/ csproj? - with the small target file along the nuget package to make it compatible with both .NET framework and .NET CoreApp? (I can send a PR for that if you want as well)

Access Violation with Code Completion

I'm trying to use the code completion features of this library. Here's a simple example:

// input is the text of my C++ source file
public static void DoCodeCompletion(string input, int row, int column)
{
    List<Completion> completions = new List<Completion>();

    string fileName = Path.GetTempFileName();
    File.WriteAllText(fileName, input);

    CXIndex index = clang.createIndex(1, 0);
    CXUnsavedFile unsavedFile;
    CXTranslationUnit tu;
    string[] arr = { "-x", "c++" };
    CXErrorCode errorCode = clang.parseTranslationUnit2(index, fileName, arr, 2, out unsavedFile, 0, (uint)CXTranslationUnit_Flags.CXTranslationUnit_PrecompiledPreamble, out tu);
    // errorCode is CXError_Success

    IntPtr pResults = clang.codeCompleteAt(tu, fileName, (uint)row, (uint)column, out unsavedFile, 0, 0);
    CXCodeCompleteResults results = Marshal.PtrToStructure<CXCodeCompleteResults>(pResults);

    // Access violation here
    clang.disposeCodeCompleteResults(out results);
    clang.disposeTranslationUnit(tu);

    File.Delete(fileName);
}
struct Adder
{
    int add(int a, int b)
    {
        return a + b;   
    }
};

void fn()
{

}

int main()
{
    Adder adder;
    adder.      <--  Initiating completion here

    return 0;
}

It results in an access violation at disposeCodeCompleteResults.

Please advise.
Thanks!

How did you get libclang.dll and libLLVM.dll

(I'm not sure an issue is the right way to deal with this but I didn't see any contact or discussion forum here or at www.clangsharp.org.)

I see at LLVMSharp that you have a nice script to generate libclang.dll and libLLVM.dll by first putting related libs into a library, running dumpbin to get the defined symbols, filtering for only the symbols you're interested in, placing them into a DEF file, and then linking the library to produce a dll.

Before I go down that path, can you tell me: If I chose to filter differently could I expose from a libclang.dll and/or libllvm.dll, that I create from a built clang/llvm, other valid entry points, such as the C++ interface to libTooling, or libASTMatchers?

Thanks! -- David

(P.S., I do have your email address due to your answer to a previous issue but I wasn't sure I was invited to use it for questions.)

CXString.ToString() in Extensions.cs

Hello,

this
public partial struct CXString
{
public override string ToString()
{
string retval = Marshal.PtrToStringAnsi(this.data);
clang.disposeString(this);
return retval;
}
}

should look like this:
public partial struct CXString
{
public override string ToString()
{
string retval = Marshal.PtrToStringAnsi(clang.getCString (this));
clang.disposeString(this);
return retval;
}
}

Took me a day to figure out, why i was getting USRs like this "ߌي�" or nulls. :D

Working with DotNetCore

Hi,
I am trying to incorporate this into a cross-platform project with dotnet core, but it keeps having an error. It says it does not support AnyCPU, and I have not found a way to set it to a specific cpu architecture. I have used and

Any help would be appreciated. Thanks!

Crash on invoking parseTranslationUnit function.

When i invoke parseTranslationUnit with the following scenario i am getting crash.
string[] args2 = new string[2];
args2[0] = "-include-pch";
args2[1] = "testfiles.h.pch";
nargs = 2;
CXTranslationUnit translationUnit;
ClangSharp.clang.
parseTranslationUnit(m_ClangIndex, "DummyFile.cpp", args2, 0, out unsavedFiles[0], 1, (uint)ClangSharp.CXTranslationUnit_Flags.CXTranslationUnit_ForSerialization);

The same call is working when i invoke from c++.

Add --include CLI option

When processing large headers like winnt.h, it is often desirable to only generate a few bindings at a time. This helps to keep PRs smaller and focused. I'd love a --include option to mirror what --exclude does: if --include is specified then essentially all symbols not in the include list should be excluded.

ClangSharp should accept an rsp file

ClangSharp should be updated to accept an rsp file so that it can handle command line handling for inputs longer than the Windows limitation (~8k characters).

How do you successfully run the "command line tests" for a clang you build yourself?

I have tried building clang/llvm myself using the documented process that uses CMake to generate Visual Studio 2013 (win64) solution and project files. I build fine (no errors) and all unit tests pass.

However, if I then attempt to run the command line tests I have ~150 "unexpected failures", all due to some kind of lock file problem.

Are these tests supposed to be able to be run on the Windows/Visual Studio platform? If so, is there anything undocumented I need to do to get them to run?

(I'm afraid my home-built clang/llvm isn't working properly ... and I'd rather discover sooner than later.)

Thanks! -- David

parseTranslationUnit doesn't take a list of CXUnsavedFile

I am trying to pass in multiple unsaved files, but it seems that parseTranslationUnit only takes a single CXUnsaved file. I saw that this was reported here:

#12

But it appears that it still doesn't accept CXUnsavedFile[].

I am using the latest version: 3.8.0
image

But as you can see, parseTranslationUnit accepts a single CXUnsavedFile
image

tokenize + disposeTokens inconsistency

I discovered that this pair of methods is not really fit each other:

[DllImport("libclang.dll", EntryPoint = "clang_tokenize", CallingConvention = CallingConvention.Cdecl)]
public static extern void tokenize(CXTranslationUnit TU, CXSourceRange Range, out IntPtr Tokens, out uint NumTokens);

[DllImport("libclang.dll", EntryPoint = "clang_disposeTokens", CallingConvention = CallingConvention.Cdecl)]
public static extern void disposeTokens(CXTranslationUnit TU, out CXToken Tokens, uint NumTokens);

In my use case I workaround it with additional export:

        private string getMacroExpression(CXCursor cursor)
        {
            var tu = clang.Cursor_getTranslationUnit(cursor);
            var range = clang.getCursorExtent(cursor);

            IntPtr pTokens;
            uint numTokens;
            clang.tokenize(tu, range, out pTokens, out numTokens);

            var sbValue = new StringBuilder();
            for (var n = 1; n < numTokens; n++)
            {
                var offset = n*Marshal.SizeOf<CXToken>();
                var token = Marshal.PtrToStructure<CXToken>(pTokens + offset);

                var tokenKind = clang.getTokenKind(token);
                if (tokenKind != CXTokenKind.CXToken_Comment)
                {
                    var spelling = clang.getTokenSpelling(tu, token).ToString();
                    ...
                }
            }

            disposeTokens(tu, pTokens, numTokens);

            return sbValue.ToString();
        }

        [DllImport(@"libclang.dll", EntryPoint = @"clang_disposeTokens", CallingConvention = CallingConvention.Cdecl)]
        private static extern void disposeTokens(CXTranslationUnit tu, IntPtr tokens, uint numTokens);

I'm just wondering is it possible to integrate different export signature in to library as entire generation is done by conventions only?
Or maybe there's even a better way to access token information?

Get pre-processed file

On the command line, clang -E test.cpp will show you the preprocessed output.

> # 1 "prog.c"
> # 1 "<built-in>" 1
> # 1 "<built-in>" 3
> # 157 "<built-in>" 3
> # 1 "<command line>" 1
> # 1 "<built-in>" 2
> # 1 "prog.c" 2
> int main (void)
> {
> int a;
> }

Is there a way to get pre-processed with ClangSharp?

Not specifying output header file (-h) casues ArgumentException

In PInvokeGeneratorConfiguration, headerFile seems to be null-checked and passed to File.ReadAllText:

https://github.com/microsoft/ClangSharp/blob/b15d4a79facfec91782abfec91236fe031c2c9df/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfiguration.cs#L54

However, the headerFile option defaults to string.Empty, meaning this check always succeeds:

https://github.com/microsoft/ClangSharp/blob/b15d4a79facfec91782abfec91236fe031c2c9df/sources/ClangSharpPInvokeGenerator/Program.cs#L329-L337

This causes the following exception if the parameter is not specified, when running the program:

System.ArgumentException: Empty path name is not legal.
Parameter name: path
   at System.IO.File.ReadAllText(String path)
   at ClangSharp.PInvokeGeneratorConfiguration..ctor(String libraryPath, String namespaceName, String outputLocation, PInvokeGeneratorConfigurationOptions options, String[] excludedNames, String headerFile, String methodClassName, String methodPrefixToStrip, IReadOnlyDictionary`2 remappedNames, String[] traversalNames) in /home/dev/Development/ClangSharp/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfiguration.cs:line 54
   at ClangSharp.Program.Run(InvocationContext context) in /home/dev/Development/ClangSharp/sources/ClangSharpPInvokeGenerator/Program.cs:line 173

Add a --setLastError CLI option

Currently, there appears to be no way to specify what native Windows API functions require the SetLastError=true property to be set on their [DllImport] bindings. The result of this is that currently none of them do, meaning the recommended way of getting the last error, Marshal.GetLastWin32Error(), will not work. It would be very useful if a new CLI setting was added that would allow me to specify said functions:

--setlasterror
SomeWindowsFuncA
SomeWindowsFuncW
AnotherWindowsFuncEx

I wrote some code that can scan Microsoft's Windows API docs repository and somewhat-intelligently search for functions that set GetLastError. https://gist.github.com/nathan-alden-sr/7abf39c6389947f6cf196b8c31bf7e02. My hope is I can run this code on a particular header folder in the docs, then copy/paste the output into the generate.rsp file like above.

Nuget Installation Fails

When attempting to install the v10.0.0-beta release I got the following errors form the Nuget package manager:

Restoring packages for NativeBindingsGenerator.csproj...
Restoring packages for NativeBindingsGenerator.csproj...
  GET https://api.nuget.org/v3-flatcontainer/clangsharp.pinvokegenerator/index.json
  OK https://api.nuget.org/v3-flatcontainer/clangsharp.pinvokegenerator/index.json 143ms
  GET https://api.nuget.org/v3-flatcontainer/clangsharp.pinvokegenerator/10.0.0-beta/clangsharp.pinvokegenerator.10.0.0-beta.nupkg
  OK https://api.nuget.org/v3-flatcontainer/clangsharp.pinvokegenerator/10.0.0-beta/clangsharp.pinvokegenerator.10.0.0-beta.nupkg 151ms
  GET https://api.nuget.org/v3-flatcontainer/clangsharp/index.json
  OK https://api.nuget.org/v3-flatcontainer/clangsharp/index.json 152ms
  GET https://api.nuget.org/v3-flatcontainer/clangsharp/10.0.0-beta/clangsharp.10.0.0-beta.nupkg
  OK https://api.nuget.org/v3-flatcontainer/clangsharp/10.0.0-beta/clangsharp.10.0.0-beta.nupkg 154ms
Installing ClangSharp 10.0.0-beta.
Installing ClangSharp.PInvokeGenerator 10.0.0-beta.
Installing NuGet package ClangSharp.PInvokeGenerator 10.0.0-beta.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.CommonProjectSystemTools.GetResultOrThrowFirstException[T](Task`1 task)
   at Microsoft.VisualStudio.ProjectSystem.Build.BuildUtilities.<>c.<<AppendFlushLoggersTask>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.Build.BuildUtilities.<>c__DisplayClass16_0.<AppendUnregisterLoggersTask>b__0(Task`1 flt)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.VisualStudio.ProjectSystem.Build.BuildProject.<BuildCoreAsync>d__97.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.VisualStudio.ProjectSystem.Build.BuildManagerHostBatchingService.<SubmitBuildAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.VisualStudio.ProjectSystem.Build.BuildProject.<BuildCoreAsync>d__97.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.Build.BuildProject.<BuildAsync>d__85.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.VisualStudio.ProjectSystem.References.ResolvableReferencesProviderBase`2.<CalculateResolvedReferenceItemsAsync>d__61.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.ConfiguredProjectCache`1.<>c__DisplayClass16_0.<<GetValueSlowAsync>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.JoinableTask.<JoinAsync>d__68.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.JoinableTask`1.<JoinAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.ConfiguredProjectCache`1.<GetValueSlowAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.References.ResolvableReferencesProviderBase`2.<GetResolvedReferenceAsync>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.References.ResolvableReferencesProviderBase`2.<>c__DisplayClass43_0.<<AddAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.JoinableTask.<JoinAsync>d__68.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.JoinableTask`1.<JoinAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.ProjectLockService.<ExecuteWithinLockAsync>d__114`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.ProjectSystem.ProjectLockService.<ExecuteWithinLockAsync>d__114`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.AwaitExtensions.ExecuteContinuationSynchronouslyAwaiter`1.GetResult()
   at Microsoft.VisualStudio.ProjectSystem.References.ResolvableReferencesProviderBase`2.<AddAsync>d__43.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.References.PackageReferencesService.<AddAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at NuGet.PackageManagement.VisualStudio.NetCorePackageReferenceProject.<InstallPackageAsync>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at NuGet.PackageManagement.NuGetPackageManager.<ExecuteBuildIntegratedProjectActionsAsync>d__78.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at NuGet.PackageManagement.NuGetPackageManager.<ExecuteNuGetProjectActionsAsync>d__76.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.PackageManagement.NuGetPackageManager.<ExecuteNuGetProjectActionsAsync>d__75.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at NuGet.PackageManagement.NuGetPackageManager.<ExecuteNuGetProjectActionsAsync>d__74.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.PackageManagement.UI.UIActionEngine.<ExecuteActionsAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at NuGet.PackageManagement.UI.UIActionEngine.<>c__DisplayClass12_0.<<PerformActionImplAsync>b__0>d.MoveNext()
Time Elapsed: 00:00:02.5083459
========== Finished ==========


Allow passing of additional namespaces to 'using' in P/Invoke Generator

Currently, ClangSharpPInvokeGenerator. generates types and methods using the NativeTypeName attribute. However, there are times when this attribute is not in the same namespace that the generated types are placed in. This makes working with the generated files harder as the developer must go in after the fact and add these additional usings manually.

As such, I suggest that there be a way to add additional usings which are included in every file generated by ClangSharpPInvokeGenerator. For example, given:

dotnet run -- --config multi-file -f /usr/include/pulse/introspect.h -h /tmp/header.txt -l libpulse -m Pulse -n TerraFX.Interop -o /tmp/generated -u TerraFX.Utilities

I would expect the generated files to contain something like this:

// this is a header
// with some copyright text

using System;
using System.Runtime.InteropServices;
using TerraFX.Utilities;

namespace TerraFX.Interop
{
    /* generated types and methods */
}

This can currently be worked around with by placing the additional usings inside of the header file, but that means they are generated out of order:

// this is a header
// with some copyright text

using TerraFX.Utilities; // we are actually still part of the header here
using System;
using System.Runtime.InteropServices;

Incorrect marshalling of CXUnsavedFile unsaved_files arguments to clang_parseTranslationUnit and friends

Currently the parameters are generated as out CXUnsavedFile however according to documentation http://clang.llvm.org/doxygen/group__CINDEX__TRANSLATION__UNIT.html it is actually an array of files (and the count is passed as separate argument)
This makes it impossible to pass more then one CXUnsavedFile

The correct form would be [MarshalAs(UnmanagedType.LPArray)] CXUnsavedFile[] @unsaved_files

This bug probably applies to all functions that take an array argument as pair of pointer to first element and count.

Inconsistent behavior of ClangSharpPInvokeGenerator

Using a simple C++ class header we get different results running the generator (we use clang 6.0, but also tested with 6.01):

`C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder
libclang: crash detected during parsing: {
'source_filename' : 'decoder.h'
'command_line_args' : ['clang', '-x', 'c++', '
C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder
Error: CXError_ASTReadError

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder
Error: CXError_ASTReadError

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder
libclang: crash detected during parsing: {
'source_filename' : 'decoder.h'
'command_line_args' : ['clang', '-x', 'c++', '
C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder
libclang: crash detected during parsing: {
'source_filename' : 'decoder.h'
'command_line_args' : ['clang', '-x', 'c++', '
C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder

C:\temp\ClangSharp\ClangSharpPInvokeGenerator\bin\Debug\netcoreapp2.0   master±  dotnet ClangSharpPInvokeGenerator.dll --f decoder.h --output decoder.cs --libraryPath x --namespace Decoder
libclang: crash detected during parsing: {
'source_filename' : 'decoder.h'
'command_line_args' : ['clang', '-x', 'c++', '`

Dll not found if RID is not specified

Hello!
For CppAst I was previously using my own libclang package mainly because ClangSharp was not providing an updated NuGet package.

Now I have switched CppAst to use the beta ClangSharp 10.0 package, but my tests failed to work as I had to run them explicitly with a RID, e.g dotnet tests -c Release -platform win-x64 while with my package I didn't have to specify anything.
But It is a bit annoying for a end-user experience to have to specify this RID...

Do you know why this is not working with the libclang package that you ship?

Make --libraryPath CLI option optional

Oftentimes there are headers that do not contain function declarations. In these cases, there is no library path to supply to ClangSharp; however, ClangSharp currently treats this parameter as required. It would be nice if the parameter was optional and only generated an error if a function declaration was encountered.

DLL not found

After adding ClangSharp to my project and writing some code, when I run the code I get a DLLNotFound exception at the first call to one of the clang object's static methods.

I need to get the clang.dll from somewhere and copy it manually to my bin/Debug folder, then my code works.

What is the intended way of working? Am I missing a dependency?

This is Win 10 / VS 2017 / .NET FW 4.5 / Web application template.

Thanks for any hints!

norbert-p

Consideration to offer ClangSharpPInvokeGenerator as .NET Core global tools

Hello Clang-Team,

hope you still looking into this repo :D

In my opinion it would be a nice idea to offer your very interesting ClangSharpPInvokeGenerator as a .NET Core global tool.

People using .NET Core simple can download it from NuGet and do sth like dotnet pinvoke ./myNativeCode . Finish.

I am not sure if you think the same way but just wanted to let you know ;)

Greetings

Anonymous bitmask fields generating with the same field name

From winnt.h:

typedef struct _ImageArchitectureHeader {
    unsigned int AmaskValue: 1;                 // 1 -> code section depends on mask bit
                                                // 0 -> new instruction depends on mask bit
    int :7;                                     // MBZ
    unsigned int AmaskShift: 8;                 // Amask bit in question for this fixup
    int :16;                                    // MBZ
    DWORD FirstEntryRVA;                        // RVA into .arch section to array of ARCHITECTURE_ENTRY's
} IMAGE_ARCHITECTURE_HEADER, *PIMAGE_ARCHITECTURE_HEADER;

turns into this:

public partial struct ImageArchitectureHeader
{
    internal uint _bitfield;

    [NativeTypeName("unsigned int : 1")]
    public uint AmaskValue
    {
        get
        {
            return _bitfield & 0x1u;
        }

        set
        {
            _bitfield = (_bitfield & ~0x1u) | (value & 0x1u);
        }
    }

    [NativeTypeName("int : 7")]
    public int field
    {
        get
        {
            return (_bitfield >> 1) & 0x7F;
        }

        set
        {
            _bitfield = (_bitfield & ~(0x7F << 1)) | ((value & 0x7F) << 1);
        }
    }

    [NativeTypeName("unsigned int : 8")]
    public uint AmaskShift
    {
        get
        {
            return (_bitfield >> 8) & 0xFFu;
        }

        set
        {
            _bitfield = (_bitfield & ~(0xFFu << 8)) | ((value & 0xFFu) << 8);
        }
    }

    [NativeTypeName("int : 16")]
    public int field
    {
        get
        {
            return (_bitfield >> 16) & 0xFFFF;
        }

        set
        {
            _bitfield = (_bitfield & ~(0xFFFF << 16)) | ((value & 0xFFFF) << 16);
        }
    }

    [NativeTypeName("DWORD")]
    public uint FirstEntryRVA;
}

thus causing a duplicate field compiler error.

Make ClangSharpPInvokeGenerator --version output native library versions

Rationale: It's a pain to specify a bunch of parameters just to check that I've got the project set up correctly.

For example, I'm trying to diagnose a few issues loading the utility library, and I'm getting this in the output:

~/Development/ClangSharp$ dotnet run --project sources/ClangSharpPInvokeGenerator/ClangSharpPInvokeGenerator.csproj --runtime debian.10-x64 --framework netcoreapp3.1 -- -f ../thermite/natives/minimp3/minimp3.h -l test -n test -o ../test.cs
Unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.DllNotFoundException: Unable to load shared library 'libClangSharp' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibClangSharp: cannot open shared object file: No such file or directory
   at ClangSharp.Interop.clangsharp.Cursor_getDeclKind(CXCursor C)
   at ClangSharp.Interop.CXCursor.get_DeclKind() in /home/dev/Development/ClangSharp/sources/ClangSharp/Interop.Extensions/CXCursor.cs:line 56
// ... and the rest of the stack trace, trimmed for clarity

Being able to run something as simple as --version would be incredibly helpful without having to ensure my paths and filenames are 100% correct every time I invoke the tool. It'd also be more useful as a complete "test" to ensure that the tool has been built correctly (which it clearly isn't in my case).

Output header file is not used for generated types in multi-file mode

When using --config multi-file, ClangSharpPInvokeGenerator does not use the header file (-h) when generating files for subtypes - only the main methods file gets the header file.

From cursory inspection, this is probably because the generated subtypes do not have any usings, and the header text is only added if there are any using directives:

https://github.com/microsoft/ClangSharp/blob/b15d4a79facfec91782abfec91236fe031c2c9df/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs#L271-L273

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.