Code Monkey home page Code Monkey logo

cppsharp's Introduction

Mono is a software platform designed to allow developers to easily create cross platform applications. It is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime.

The Mono project is part of the .NET Foundation

Join us on Discord in the #monovm channel:

Contents

  1. Compilation and Installation
  2. Using Mono
  3. Directory Roadmap
  4. Contributing to Mono
  5. Reporting bugs
  6. Configuration Options
  7. Working with Submodules

Build Status

Public CI: Azure Pipelines

Legacy Jenkins CI (no longer available publicly):

OS Architecture Status
Debian 9 amd64 debian-9-amd64
Debian 9 i386 debian-9-i386
Debian 9 armel debian-9-armel
Debian 9 armhf debian-9-armhf
Debian 9 arm64 debian-9-arm64
OS X amd64 osx-amd64
OS X i386 osx-i386
Windows amd64 windows-amd64
Windows i386 windows-i386
CentOS s390x (cs) centos-s390x
Debian 9 ppc64el (cs) debian-9-ppc64el
AIX 6.1 ppc64 (cs) aix-ppc64
FreeBSD 12 amd64 (cs) freebsd-amd64

(cs) = community supported architecture

Compilation and Installation

Building the Software

Please see our guides for building Mono on Mac OS X, Linux and Windows.

Note that building from Git assumes that you already have Mono installed, so please download and install the latest Mono release before trying to build from Git. This is required because the Mono build relies on a working Mono C# compiler to compile itself (also known as bootstrapping).

If you don't have a working Mono installation

If you don't have a working Mono installation, you can try a slightly more risky approach: getting the latest version of the 'monolite' distribution, which contains just enough to run the 'mcs' compiler. You do this with:

# Run the following line after ./autogen.sh
make get-monolite-latest

This will download and place the files appropriately so that you can then just run:

make

The build will then use the files downloaded by make get-monolite-latest.

Testing and Installation

You can run the mono and mcs test suites with the command: make check.

Expect to find a few test suite failures. As a sanity check, you can compare the failures you got with https://jenkins.mono-project.com/.

You can now install mono with: make install

You can verify your installation by using the mono-test-install script, it can diagnose some common problems with Mono's install. Failure to follow these steps may result in a broken installation.

Using Mono

Once you have installed the software, you can run a few programs:

  • mono program.exe runtime engine

  • mcs program.cs C# compiler

  • monodis program.exe CIL Disassembler

See the man pages for mono(1), mcs(1) and monodis(1) for further details.

Directory Roadmap

  • acceptance-tests/ - Optional third party test suites used to validate Mono against a wider range of test cases.

  • data/ - Configuration files installed as part of the Mono runtime.

  • docs/ - Technical documents about the Mono runtime.

  • external/ - Git submodules for external libraries (Newtonsoft.Json, ikvm, etc).

  • ikvm-native/ - Glue code for ikvm.

  • libgc/ - The (deprecated) Boehm GC implementation.

  • llvm/ - Utility Makefiles for integrating the Mono LLVM fork.

  • m4/ - General utility Makefiles.

  • man/ - Manual pages for the various Mono commands and programs.

  • mcs/ - The class libraries, compiler and tools

    • class/ - The class libraries (like System.*, Microsoft.Build, etc.)

    • mcs/ - The Mono C# compiler written in C#

    • tools/ - Tools like gacutil, ikdasm, mdoc, etc.

  • mono/ - The core of the Mono Runtime.

    • arch/ - Architecture specific portions.

    • benchmark/ - A collection of benchmarks.

    • btls/ - Build files for the BTLS library which incorporates BoringSSL.

    • cil/ - Common Intermediate Representation, XML definition of the CIL bytecodes.

    • dis/ - CIL executable Disassembler.

    • eglib/ - Independent implementation of the glib API.

    • metadata/ - The object system and metadata reader.

    • mini/ - The Just in Time Compiler.

    • profiler/ - The profiler implementation.

    • sgen/ - The SGen Garbage Collector implementation.

    • tests/ - The main runtime tests.

    • unit-tests/ - Additional runtime unit tests.

    • utils/ - Utility functions used across the runtime codebase.

  • msvc/ - Logic for the MSVC / Visual Studio based runtime and BCL build system. The latter is experimental at the moment.

  • packaging/ - Packaging logic for the OS X and Windows Mono packages.

  • po/ - Translation files.

  • runtime/ - A directory that contains the Makefiles that link the mono/ and mcs/ build systems.

  • samples/ - Some simple sample programs on uses of the Mono runtime as an embedded library.

  • scripts/ - Scripts used to invoke Mono and the corresponding program.

  • support/ - Various support libraries.

  • tools/ - A collection of tools, mostly used during Mono development.

Contributing to Mono

Before submitting changes to Mono, please review the contribution guidelines. Please pay particular attention to the Important Rules section.

Reporting bugs

To submit bug reports, please open an issue on the mono GitHub repo.

Please use the search facility to ensure the same bug hasn't already been submitted and follow our guidelines on how to make a good bug report.

Configuration Options

The following are the configuration options that someone building Mono might want to use:

  • --with-sgen=yes,no - Generational GC support: Used to enable or disable the compilation of a Mono runtime with the SGen garbage collector.

    • On platforms that support it, after building Mono, you will have both a mono-boehm binary and a mono-sgen binary. mono-boehm uses Boehm, while mono-sgen uses the Simple Generational GC.
  • --with-libgc=[included, none] - Selects the default Boehm garbage collector engine to use.

    • included: (slightly modified Boehm GC) This is the default value for the Boehm GC, and it's the most feature complete, it will allow Mono to use typed allocations and support the debugger.

    • none: Disables the inclusion of a Boehm garbage collector.

    • This defaults to included.

  • --enable-cooperative-suspend

    • If you pass this flag the Mono runtime is configured to only use the cooperative mode of the garbage collector. If you do not pass this flag, then you can control at runtime the use of the cooperative GC mode by setting the MONO_ENABLE_COOP_SUSPEND flag.
  • --with-tls=__thread,pthread

    • Controls how Mono should access thread local storage, pthread forces Mono to use the pthread APIs, while __thread uses compiler-optimized access to it.

    • Although __thread is faster, it requires support from the compiler, kernel and libc. Old Linux systems do not support with __thread.

    • This value is typically pre-configured and there is no need to set it, unless you are trying to debug a problem.

  • --with-sigaltstack=yes,no

    • Experimental: Use at your own risk, it is known to cause problems with garbage collection and is hard to reproduce those bugs.

    • This controls whether Mono will install a special signal handler to handle stack overflows. If set to yes, it will turn stack overflows into the StackOverflowException. Otherwise when a stack overflow happens, your program will receive a segmentation fault.

    • The configure script will try to detect if your operating system supports this. Some older Linux systems do not support this feature, or you might want to override the auto-detection.

  • --with-static_mono=yes,no

    • This controls whether mono should link against a static library (libmono.a) or a shared library (libmono.so).

    • This defaults to yes, and will improve the performance of the mono program.

    • This only affects the `mono' binary, the shared library libmono.so will always be produced for developers that want to embed the runtime in their application.

  • --with-xen-opt=yes,no - Optimize code for Xen virtualization.

    • It makes Mono generate code which might be slightly slower on average systems, but the resulting executable will run faster under the Xen virtualization system.

    • This defaults to yes.

  • --with-large-heap=yes,no - Enable support for GC heaps larger than 3GB.

    • This only applies only to the Boehm garbage collector, the SGen garbage collector does not use this configuration option.

    • This defaults to no.

  • --enable-small-config=yes,no - Enable some tweaks to reduce memory usage and disk footprint at the expense of some capabilities.

    • Typically this means that the number of threads that can be created is limited (256), that the maximum heap size is also reduced (256 MB) and other such limitations that still make mono useful, but more suitable to embedded devices (like mobile phones).

    • This defaults to no.

  • --with-ikvm-native=yes,no - Controls whether the IKVM JNI interface library is built or not.

    • This is used if you are planning on using the IKVM Java Virtual machine with Mono.

    • This defaults to yes.

  • --with-profile4=yes,no - Whether you want to build the 4.x profile libraries and runtime.

    • This defaults to yes.
  • --with-libgdiplus=installed,sibling,<path> - Configure where Mono searches for libgdiplus when running System.Drawing tests.

    • It defaults to installed, which means that the library is available to Mono through the regular system setup.

    • sibling can be used to specify that a libgdiplus that resides as a sibling of this directory (mono) should be used.

  • Or you can specify a path to a libgdiplus.

  • --enable-minimal=LIST

    • Use this feature to specify optional runtime components that you might not want to include. This is only useful for developers embedding Mono that require a subset of Mono functionality.

    • The list is a comma-separated list of components that should be removed, these are:

      • aot: Disables support for the Ahead of Time compilation.

      • attach: Support for the Mono.Management assembly and the VMAttach API (allowing code to be injected into a target VM)

      • com: Disables COM support.

      • debug: Drop debugging support.

      • decimal: Disables support for System.Decimal.

      • full_messages: By default Mono comes with a full table of messages for error codes. This feature turns off uncommon error messages and reduces the runtime size.

      • generics: Generics support. Disabling this will not allow Mono to run any 2.0 libraries or code that contains generics.

      • jit: Removes the JIT engine from the build, this reduces the executable size, and requires that all code executed by the virtual machine be compiled with Full AOT before execution.

      • large_code: Disables support for large assemblies.

      • logging: Disables support for debug logging.

      • pinvoke: Support for Platform Invocation services, disabling this will drop support for any libraries using DllImport.

      • portability: Removes support for MONO_IOMAP, the environment variables for simplifying porting applications that are case-insensitive and that mix the Unix and Windows path separators.

      • profiler: Disables support for the default profiler.

      • reflection_emit: Drop System.Reflection.Emit support

      • reflection_emit_save: Drop support for saving dynamically created assemblies (AssemblyBuilderAccess.Save) in System.Reflection.Emit.

      • shadow_copy: Disables support for AppDomain's shadow copies (you can disable this if you do not plan on using appdomains).

      • simd: Disables support for the Mono.SIMD intrinsics library.

      • ssa: Disables compilation for the SSA optimization framework, and the various SSA-based optimizations.

  • --enable-llvm

    • This enables the use of LLVM as a code generation engine for Mono. The LLVM code generator and optimizer will be used instead of Mono's built-in code generator for both Just in Time and Ahead of Time compilations.

    • See https://www.mono-project.com/docs/advanced/mono-llvm/ for the full details and up-to-date information on this feature.

    • You will need to have an LLVM built that Mono can link against.

  • --enable-big-arrays - Enable use of arrays with indexes larger than Int32.MaxValue.

    • By default Mono has the same limitation as .NET on Win32 and Win64 and limits array indexes to 32-bit values (even on 64-bit systems).

    • In certain scenarios where large arrays are required, you can pass this flag and Mono will be built to support 64-bit arrays.

    • This is not the default as it breaks the C embedding ABI that we have exposed through the Mono development cycle.

  • --enable-parallel-mark

    • Use this option to enable the garbage collector to use multiple CPUs to do its work. This helps performance on multi-CPU machines as the work is divided across CPUS.

    • This option is not currently the default on OSX as it runs into issues there.

    • This option only applies to the Boehm GC.

  • --enable-dtrace

    • On Solaris and MacOS X builds a version of the Mono runtime that contains DTrace probes and can participate in the system profiling using DTrace.
  • --disable-dev-random

    • Mono uses /dev/random to obtain good random data for any source that requires random numbers. If your system does not support this, you might want to disable it.

    • There are a number of runtime options to control this also, see the man page.

  • --with-csc=roslyn,mcs,default

    • Use this option to configure which C# compiler to use. By default the configure script will pick Roslyn, except on platforms where Roslyn does not work (Big Endian systems) where it will pick mcs.

      If you specify "mcs", then Mono's C# compiler will be used. This also allows for a complete bootstrap of Mono's core compiler and core libraries from source.

  If you specify "roslyn", then Roslyn's C# compiler will be used. This currently uses Roslyn binaries.

  • --enable-nacl

    • This configures the Mono compiler to generate code suitable to be used by Google's Native Client: https://code.google.com/p/nativeclient/

    • Currently this is used with Mono's AOT engine as Native Client does not support JIT engines yet.

  • --enable-wasm

    • Use this option to configure mono to run on WebAssembly. It will set both host and target to the WebAssembly triplet. This overrides the values passed to --host or --target and ignored what config.sub guesses.

      This is a workaround to enable usage of old automake versions that don't recognize the wasm triplet.

Working With Submodules

Mono references several external git submodules, for example a fork of Microsoft's reference source code that has been altered to be suitable for use with the Mono runtime.

This section describes how to use it.

An initial clone should be done recursively so all submodules will also be cloned in a single pass:

$ git clone --recursive [email protected]:mono/mono

Once cloned, submodules can be updated to pull down the latest changes. This can also be done after an initial non-recursive clone:

$ git submodule update --init --recursive

To pull external changes into a submodule:

$ cd <submodule>
$ git pull origin <branch>
$ cd <top-level>
$ git add <submodule>
$ git commit

By default, submodules are detached because they point to a specific commit. Use git checkout to move back to a branch before making changes:

$ cd <submodule>
$ git checkout <branch>
# work as normal; the submodule is a normal repo
$ git commit/push new changes to the repo (submodule)

$ cd <top-level>
$ git add <submodule> # this will record the new commits to the submodule
$ git commit

To switch the repo of a submodule (this should not be a common or normal thing to do at all), first edit .gitmodules to point to the new location, then:

$ git submodule sync -- <path of the submodule>
$ git submodule update --recursive
$ git checkout <desired new hash or branch>

The desired output diff is a change in .gitmodules to reflect the change in the remote URL, and a change in / where you see the desired change in the commit hash.

License

See the LICENSE file for licensing information, and the PATENTS.TXT file for information about Microsoft's patent grant.

Mono Trademark Use Policy

The use of trademarks and logos for Mono can be found here.

cppsharp's People

Contributors

azeno avatar chkn avatar ddobrev avatar deadlocklogic avatar elonh avatar esdrubal avatar fsinisi90 avatar genuinelucifer avatar golddranks avatar iife avatar josetr avatar jpnoir avatar konistehrad avatar mohtamohit avatar oysteinkrog avatar realvictorprm avatar rokups avatar saalvage avatar shana avatar stephenatwork avatar sundermann avatar tapika avatar tomba avatar tomspilman avatar tritao avatar trungnt2910 avatar vargaz avatar vovkasm avatar xistoso avatar zillemarco 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  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

cppsharp's Issues

Static Functions Issues

I'm having issues with exporting static functions from C++ without getting weird looking wrappers.

My first try was just adding static methods to a class with private constructor. My thinking was that since the class had nothing but static methods, CppSharp would not make it constructible.... but that does not seem to be the case. The final class had constructors and dispose methods.

My next try was just putting plain methods in a header:

// MyStaticClass.h
#pragma once
#include "PreDecls.h"

__declspec(dllexport) bool MyStaticMethod();

What I got was this...

namespace MyNamespace
{
    public unsafe partial class MyNamespace_MyStaticClass
    {
        public struct Internal
        {
           // blah blah blah
        }

        public static bool MyStaticMethod()
        {
            var __ret = Internal.MyStaticMethod_0();
            return __ret;
        }
    }
}

Instead of having the class named after the header file... MyStaticClass... I got something with the assembly namespace prepended MyNamespace_MyStaticClass.

So what is the best way to get a C# style "static class" wrapper from C++?

Can't wrap operator*

Operator* will need to be renamed in the bindings. It currently generates

public static void* operator *(SmartPtr __op)

from

struct SmartPtr
{
    void* operator*() { return nullptr; }
};

SDL Example Crash

Building against LLVM/Clang r185136 the SDL example crashes under VS2012.

The crash is in ASTVisitor.VisitParameterDecl:

        public virtual bool VisitParameterDecl(Parameter parameter)
        {
            if (!VisitDeclaration(parameter))
                return false; 

            return parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers); //< CRASH!
        }

It is caused by parameter.Type being null. Inspecting the parameter.Name it is "argv" and that it is trying to process the "SDL_main" function.

Not sure if this error should be more gracefully handled?

Maybe the sample should skip processing SDL_main.h?

Underscores In OutputNamespace

If I do the following:

options.OutputNamespace = "Company.Product.Library";

The generated namespace is:

namespace Company_Product_Library
{

.. and not what I expected which is...

namespace Company.Product.Library
{

This seems to be caused by using SafeIdentifier on the namespace string.

MinGW symbols not found

While wrapping QtCore, no symbol is found. The searched for symbols (that is, the parameter "symbol" of Library.FindSymbol) have a format similar to:

??0QForeachContainerBase@@qeaa@XZ

while the keys of Library.Symbols are of the formats:

__imp___Zls6QDebugRK21QPersistentModelIndex
_z_inflatePrime

Changing Driver.Options.Abi to Itanium (the default is Microsoft) makes no difference.

No Destructor Generated?

I have the following class:

class __declspec(dllexport) MyClass
{        
public:
    MyClass();
    ~MyClass();
};

... after generation the dispose methods look like this:

        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            Marshal.FreeHGlobal(__Instance);
        }

I don't see it trying to execute my destructor method at all.

SDL Example Fails For Unions

The SDL example now runs into some unions when processing.

In particular in SDL_RWops...

typedef struct SDL_RWops
{
    union
    {
#if defined(ANDROID)
        struct
        {
            void *fileNameRef;

In SDL_Event....

/**
 *  \brief General event structure
 */
typedef union SDL_Event
{

In SDL_HapticEffect....

typedef union SDL_HapticEffect
{
    /* Common for all force feedback effects */
    Uint16 type;                    /**< Effect type. */
    SDL_HapticConstant constant;    /**< Constant effect. */

In SDL_GameControllerButtonBind:

typedef struct SDL_GameControllerButtonBind
{
    SDL_GameControllerBindType bindType;
    union
    {
        int button;
        int axis;

Parser::ParseSharedLib depends on unimplemented function

I'm trying to use a library, "vc100-liboctave-1.dll" (part of a standard windows Octave install), but I'm getting the following error:

For this function:

ParserResultKind Parser::ParseSharedLib(llvm::StringRef File,
                                            llvm::MemoryBuffer *Buffer)

this line:

for(auto it = Object->begin_dynamic_symbols(); it != Object->end_dynamic_symbols();

depends on unimplemented function:

symbol_iterator COFFObjectFile::begin_dynamic_symbols() const {
  // TODO: implement
  report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
}

Syntax Errors In Generator.Tests

There are some syntax errors in the current Generator.Tests library that I don't know how to fix myself.

First in TestPasses.cs you have this:

        [SetUp]
        public void Setup()
        {
            ParseLibrary("Passes.h");
            passBuilder = new PassBuilder(library); // < ERROR!  PassBuilder needs a Driver now!
        }

Then in TestCLITypePrinter.cs:

        [TestFixtureSetUp]
        public void Init()
        {
            ParseLibrary("CLITypes.h");
            printer = new CLITypePrinter(database, library); // < ERROR! needs a Driver and a CLITypePrinterContext!
        }

Error from STL Library

My C++ code contains Standard Library functions and I am having a trouble running CppSharp due to that.
On my header file, I have something like:
int testFunc(std::string x);

Then my C# code, I did similar as what the example did, include Library and header files with correct directory. After running the problem, I get errors like:

error CS0246: The type or namespace name 'std' could not be f
ound (are you missing a using directive or an assembly reference?)

error CS0208: Cannot take the address of, get the size of, or
declare a pointer to a managed type ('std.basic_string.Internal')
c:\Users

error CS1061: 'Std.String' does not contain a definition for
__Instance' and no extension method __Instance' accepting a first argument of
type 'Std.String' could be found (are you missing a using directive or an assem
bly reference?)

When I look at the .cs file, it generates to:
internal static extern int testFunc1_0(global::System.IntPtr instance, Std.String x);

I just downloaded the latest VS dlls (Nov 13th ver 423). I am also having similar error messages when I use stl , and others. Do I need to do some customization or something? How to make CppSharp recognizes my STL stuff? Thanks

Null reference exception when parsing header

I'm happy to help debug the below error, I'm just not sure where to start.

I'm trying to generate wrappers for the octave libraries (). I'm getting the null reference exception below. The null is generated on line 505 of parser.cpp (VTLayout is null):

auto& VTLayout = VTContext.getVFTableLayout(RD, VFPtrInfo.VFPtrOffset);

Here is the exception:

System.NullReferenceException occurred
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=CppSharp.Parser
StackTrace:
at llvm.OwningArrayPtrclang::VTableComponent.get(OwningArrayPtrclang::VTableComponent* ) in c:\cppsharp\cppsharp\deps\llvm\include\llvm\adt\owningptr.h:line 135
InnerException:

Here is my setup code:

    public void Setup(Driver driver)
    {
        var options = driver.Options;
        options.LibraryName = "OctaveSharp";
        options.Headers.Add("oct.h");
        options.IncludeDirs.Add(@"C:\Octave-class\3.2.4_gcc-4.4.0\include\octave-3.2.4\octave");
        options.LibraryDirs.Add(@"C:\Software\Octave-3.6.4\lib\octave\3.6.4");
        options.Libraries.Add(@"octave.lib");
        options.OutputDir = @"C:\CppSharp\CppSharp\OctaveSharp";
    }

Octave was installed using:
http://sourceforge.net/projects/octave/files/Octave%20Windows%20binaries/Octave%203.6.4%20for%20Windows%20Microsoft%20Visual%20Studio/

OSX Support

I've had trouble with building and using this on OSX. Ultimately I have compiled the projects, but I have problems with unresolved symbols for ASTContext (_ZN8CppSharp9CppParser3AST10ASTContextC2Ev). The constructor is not defined in AST.h, so I'm not sure how this was generated in AST.cs. I can go and add in an empty constructor for ASTContext, but then I get some other errors due to null values somewhere...

Does anyone have some clearer instructions on how to get the OSX build up?

Unhandled Exception:
System.NotSupportedException: Original pointer must not be null
  at CppSharp.DeclConverter.Visit (CppSharp.Parser.AST.Declaration decl) [0x00000] in <filename unknown>:0
  at CppSharp.DeclConverter.VisitDeclaration (CppSharp.Parser.AST.Declaration decl, CppSharp.AST.Declaration _decl) [0x00000] in <filename unknown>:0
  at CppSharp.DeclConverter.VisitTranslationUnit (CppSharp.Parser.AST.TranslationUnit decl) [0x00000] in <filename unknown>:0
  at CppSharp.DeclVisitor`1[CppSharp.AST.Declaration].Visit (CppSharp.Parser.AST.Declaration decl) [0x00000] in <filename unknown>:0
  at CppSharp.DeclConverter.Visit (CppSharp.Parser.AST.Declaration decl) [0x00000] in <filename unknown>:0
  at CppSharp.ASTConverter.Convert () [0x00000] in <filename unknown>:0
  at CppSharp.ClangParser.ConvertASTContext (CppSharp.Parser.AST.ASTContext context) [0x00000] in <filename unknown>:0
  at CppSharp.Driver.ParseCode () [0x00000] in <filename unknown>:0
  at CppSharp.ConsoleDriver.Run (ILibrary library) [0x00000] in <filename unknown>:0
  at Crap.Test+Program.Main (System.String[] args) [0x00000] in <filename unknown>:0

Handle non-TagDecl bases

BaseClassSpecifier.Class has the following code:
if (!Type.IsTagDecl(out @Class))
throw new NotSupportedException();

Which means generation fails for classes which inherit templates. This branch adds a test case to the Basic test.

It also has hacks to early out for non-TagDecl bases which at least allows generation to succeed. Should I make a pull request or is there a better way to handle this?

https://github.com/sk-havok/CppSharp/tree/req/non_class_base

Finalizers

It would be nice for CppSharp to generate C# finalizers for all wrapped objects. I currently work around this by adding them to a separate source file as a partial class implementation:

    public unsafe partial class Texture
    {
        ~Texture()
        {
            Dispose(false);
        }
    }

    public unsafe partial class RenderTarget
    {
        ~RenderTarget()
        {
            Dispose(false);
        }
    }

The finalizer is necessary to properly cleanup the unmanaged parts of the wrapper when the user omits a direct call to Dispose(). You already call GC.SuppressFinalize(this) which means the finalizer will not do any extra work unless it is needed.

Some people prefer to not have finalizers and instead force the caller to properly dispose of their objects. In this case adding a finalizer could be optional and when disabled it could add something like this instead:

#if DEBUG
    ~WrapperClass()
    {
        Debug.Fail("You forgot to call Dispose!");
    }
#endif

To alert the user that they forgot to Dispose() this object and that the unmanaged objects were leaked.

By the way we're using CppSharp to generate C# wrappers for a project running on the PS4. It has been fantastic and much easier than if we needed to generate our own bindings.

How to get started with CppSharp in a Win32 Dynamic Library like this ?

一个.h文件DllDemo.h

ifdef DllDemo_EXPORTS

define DllAPI __declspec(dllexport)

else

define DllAPI __declspec(dllimport)

extern "C" //原样编译
{
DllAPI int __stdcall Max(int a,int b); //__stdcall使非C/C++语言内能够调用API
}

endif

在DllDemo.cpp文件中导入DllDemo.h文件,并实现Max(int,int)函数

include "DllDemo.h"

DllAPI int __stdcall Max(int a,int b)
{
if(a==b)
return NULL;
else if(a>b)
return a;
else
return b;
}

Functions not found in the library symbols

They are many, here's just 3 examples: QModelIndex::row(), QModelIndex::column(), QModelIndex::model(). Using Qt MinGW 5.1.0 with:

driver.Options.GeneratorKind = LanguageGeneratorKind.CSharp;
string qtModule = "QtCore";
driver.Options.Abi = CppAbi.Itanium;
driver.Options.LibraryName = string.Format("{0}Sharp", qtModule);
driver.Options.Verbose = true;
driver.Options.IgnoreParseWarnings = true;
driver.Options.Headers.Add("qabstractitemmodel.h");
driver.Options.IncludeDirs.Add(@"C:\Qt\Qt5.1.0\5.1.0\mingw48_32\include");
driver.Options.IncludeDirs.Add(Path.Combine(@"C:\Qt\Qt5.1.0\5.1.0\mingw48_32\include", qtModule));
driver.Options.LibraryDirs.Add(@"C:\Qt\Qt5.1.0\5.1.0\mingw48_32\lib");
driver.Options.Libraries.Add("libQt5Core.a");
driver.Options.Defines.Add("_MSC_FULL_VER=170050215");

String Memory Leak

I noticed this in one of our wrapped functions:

        protected Effect(string name)
        {
            var arg0 = Marshal.StringToHGlobalAnsi(name);
            __Instance = Marshal.AllocHGlobal(88);
            Internal.ctor_0(__Instance, arg0);
        }

Here you use Marshal.StringToHGlobalAnsi to marshal the string to C++, but you don't free the string. From the docs it says that you should be calling Marshal.FreeHGlobal(arg0); to free that memory.

I suspect this is a memory leak in CppSharp.

Null ref at Enumeration.Item.IsHexadecimal with qmetatype.h

The problem is that most enum members of QMetaType::Type are defined using a macro, that is:

enum Type {
    // these are merged with QVariant
    QT_FOR_EACH_STATIC_TYPE(QT_DEFINE_METATYPE_ID)

    FirstCoreType = Bool,
    LastCoreType = QJsonDocument,
    FirstGuiType = QFont,
    LastGuiType = QPolygonF,
    FirstWidgetsType = QSizePolicy,
    LastWidgetsType = QSizePolicy,
    HighestInternalId = LastWidgetsType,

    QReal = sizeof(qreal) == sizeof(double) ? Double : Float,

    UnknownType = 0,
    User = 1024
};

I'd think the macro would have to be expanded before working with the items of the enum.

Wrong parameters of operators generated by Q_DECLARE_OPERATORS_FOR_FLAGS

To reproduce, run the latest Qt# (https://github.com/ddobrev/QtSharp/) and check, for example, QtCoreqstring.operator_. This is the | operator (you can see the internal call), apparently generated by Q_DECLARE_OPERATORS_FOR_FLAGS - there is no other | operator in qstring.h. Its parameters are of type Qt.MouseButton. At the same time, one can see that the call to Q_DECLARE_OPERATORS_FOR_FLAGS is given as its argument QString::SectionFlags.
Note: Qt.MouseButton is used as the incorrect replacement in all cases.

Unsafe Externs

I was getting errors from the usage of unsafe in the SDL example like so:

            [SuppressUnmanagedCodeSecurity]
            [DllImport("SymbolNotFound", CallingConvention = CallingConvention.Cdecl,
                EntryPoint="SDL_NumJoysticks")]
            public unsafe static extern int NumJoysticks0();

But really... unsafe is not needed here... that code compiles fine without the unsafe keyword.

Should GenerateInternalFunction be fixed to not put unsafe on all externs?

windows.h not found

In the native header I reference a third party library that uses

#include <windows.h>

I use

options.IncludeDirs.Add("PATH_TO_3RDPARTY_DIR"); 

and

ctx.IgnoreHeadersWithName("HEADER_NAME");

this works with the CppSharp_VS2012_423 release but using the latest 933 build from Teamcity I get:

fatal windows.h file not found 

and the bindings are not produced. Is this a clang problem or cppSharp?

wrapping interface-based libraries

It seems CppSharp is unable to wrap interface-based libraries. It outputs lots of "Symbol not found" warnings with mangled names. These mangled names are not exported of course. Library exports only few functions and provides header files full of pure virtual declarations of methods. User does not create library objects either - calls to library api return created objects. Tested with this: http://downloads.sourceforge.net/irrlicht/irrlicht-1.8.zip and oct 25 binary release.

Include a known-good llvm revision

Because CppSharp requires a trunk version of llvm it would be nice to keep the an up to date known-good revision number in the version getting started docs.

LLVM/Clang Latest Breaks CppSharp

So after hours of trying to get CppSharp to build I've gotten close, but found out finally that the latest changes to LLVM/Clang break CppSharp.

I'm working on a PR to fix this now.

Error when parsing headers referenced includes.

Just want to say, awesome project. Great concept, and it is unbelievable how easy you have made it for others.

I do have a question though. When CppSharp parses the headers I specify, I get an error about the headers that are referenced within the .h file, saying they can not be found. Mainly when they are in this format: "includes/types.h"

I am adding a folder for the includes as such:

options.IncludeDirs.Add(@"C:\Users\Joe\Documents\Testapp\lib\includes");

Then adding each header as such:

options.Headers.Add("interface.h");

Now I know I could bypass this, but I am wondering if their is a way to set ignore parameters on headers. So I could ignore certain strings? Unless there is another way of fixing this.

Support dependent fields in internals

We need to handle cases such as:

template
class Whatever
{
T Foo;
}

class Bar
{
Whatever W;
}

In here, Foo is a dependent field. We need to represent it in Internals as an int. One of the approaches is generating a separate internal struct per template specialisation.

Multiple identifiers have same name.

For example this is generated when trying to wrap irrlicht:

[SuppressUnmanagedCodeSecurity]
[UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.ThisCall)]
delegate void __IGUIButtonDelegate(global::System.IntPtr instance);
static __IGUIButtonDelegate __IGUIButtonDelegateInstance;

static void __IGUIButtonDelegateHook(global::System.IntPtr instance)
{
    if (!_References.ContainsKey(instance))
        throw new Exception("No managed instance was found");

        var target = (IGUIButton) _References[instance].Target;
        target.Dispose();
}

[SuppressUnmanagedCodeSecurity]
[UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.ThisCall)]
delegate void __IGUIButtonDelegate(global::System.IntPtr instance);
static __IGUIButtonDelegate __IGUIButtonDelegateInstance;

static void __IGUIButtonDelegateHook(global::System.IntPtr instance)
{
    if (!_References.ContainsKey(instance))
        throw new Exception("No managed instance was found");

    var target = (IGUIButton) _References[instance].Target;
    target.Dispose();
}

Other files have only repeated delegate type definitions.
Used config:

options.Abi = CppAbi.Microsoft;
options.GenerateInterfacesForMultipleInheritance = true; 
options.GenerateVirtualTables = true;
options.CheckSymbols = false;

Const and non-const constructor overloads

When signatures clash, they're given an ordinal to disambiguate them. This doesn't work for constructors however.

struct Overloaded
{
    Overloaded(void* p) {}
    Overloaded(const void* p) {}
};

I'm not sure what the best answer for this is. Add extra discriminant parameters or fallback to runtime dispatch?

public void Overloaded(void* p, int isConst) // runtime
{
     var arg0 = p;
     if(isConst) Internal._Overloaded0(__Instance, arg0);
     else Internal._Overloaded1(__Instance, arg0);
}
public void Overloaded(void* p, Const.True)
public void Overloaded(void* p, Const.False)

I'm not familiar with c# generics but perhaps there's a solution there?

Need a way to indicate that one header depends on the macros in another header

I have two headers where one header depends on the macros defined in the other header, but the second header doesn't include the first header. The assumption is that the first header will always be included in a file before the second header. As a result, I'm getting errors in the second header.

Currently I am resolving this issue by creating a third header which includes the other two headers in the appropriate order. It would be nice to have some way of indicating this dependency in code rather than having to create another header.

How to pass string by reference?

I have the following simple method

void Test(char* output)
{
   output = strdup("This is a test");
}

How can I make the generator produce something like:

internal static extern void Test_0(global::System.IntPtr instance, out string output);

Currently it produces something like:

internal static extern void Test_0(global::System.IntPtr instance, sbyte* output);

and if you add the following line to Preprocess

ctx.SetMethodParameterUsage("Foo", "Test", 1, ParameterUsage.Out);

it will produce

internal static extern void Test_0(global::System.IntPtr instance, out sbyte output);

Generating bindings for C library/ABI

What is the story if I want to generate bindings for e.g. ffmpeg?
Having a "C" mode seems like a very useful thing to me, is this something that is a goal/desired? (I'm really tired of creating p/invoke stuff by hand ...)

I have not found a way to generate nice C bindings using the existing options, but I've been able to get calling convention etc. correct by modifying Parser.cpp to pass -std=gnu99.
I guess there might be some work needed other places as well to get things working, any ideas/suggestions?

Correct Location to Run Cmake

The docs say:
4.Run CMake in \deps\llvm and compile solution in RelWithDebInfo mode

which results in the .lib files being put in "deps\llvm\RelWithDebInfo" , but the CppSharp project is looking in "deps\llvm\build\RelWithDebInfo". Am I supposed to run Cmake in the build folder?

EntryPointNotFoundException with a simple example

I am testing the usage of the library (CppSharp_VS2012_423_artifacts.zip) with a simple project in VS2012.
I have the following three projects based on some test projects you have in the repository:
Native.vcxproj with Native.h

#if defined(_MSC_VER)
#define DLL_API __declspec(dllexport)
#else
#define DLL_API
#endif

class DLL_API Foo
{
public:
     Foo();
     int A;
     float B;
const char* GetANSI();
};

and Native.cpp

#include "Native.h"  

const char* Foo::GetANSI()
{
 return "ANSI";
}

WrapperGenerator with Program.cs

using System;
using CppSharp;
using CppSharp.AST;
using CppSharp.Generators;

namespace WrapperGenerator
{
       class Program : ILibrary
      {
           static void Main(string[] args)
           {
                 ConsoleDriver.Run(new Program());
                 Console.ReadLine();
            }

           public void Setup(Driver driver)
           {            
        var options = driver.Options;
        options.Verbose = true;
        options.GeneratorKind = GeneratorKind.CSharp;          
        options.LibraryName = "Native";           
        options.Headers.Add(@"F:\Repositories\TestCppSharp\Source\Native\Native.h");
        options.OutputDir = @"F:\Repositories\TestCppSharp\Source\TestCppSharp\";            
        //options.TargetTriple = "i686-pc-win32";          
    }

    public void SetupPasses(Driver driver) { }
    public void Preprocess(Driver driver, ASTContext ctx)  { }
    public void Postprocess(Driver driver, ASTContext ctx) { }
   }

}

The Native.cs file is generated successfully and I have the following simple program in another project TestCppSharp

using System;
using Native;

 namespace TestCppSharp
 {
      class Program
     {
           static void Main(string[] args)
           {
                   Native.Foo d = new Foo();
                   Console.WriteLine(d.GetANSI());
           }
     }
  }

When I run this I get EntryPointNotFoundException inside Native.cs in

    public Foo()
    {
        __Instance = Marshal.AllocHGlobal(8);
        Internal.ctor_0(__Instance);
    }

Any ideas what might be wrong? Also, is the current Getting-Started documentation up-do-date? I could help with that if you want. In that guide the generated code does not include CppSharp.Runtime.ICppMarshal interface. Is it possible to do that in my example?

Receiving alot of errors when parsing

When trying to generate both CLI and C# wrappers I receive many errors for a couple of projects. So I am trying to figure out if I am doing something wrong here. The errors I seem to be receiving are:

Unhandled typdef errors
Duplicate names
Unknown typename

I know duplicate names is just a warning, but when I look at some of the files generated a large portion of it is generic names from the renaming. For the most part it generates the proper files, except it seems like it is not generating any files for the headers that are receiving the Unknown typename errors. Which is a large portion of one of the libraries. Is there any way I can minimize these errors, possible some extra steps that I can take. so I can have functional wrappers?

I am not using any SetupPasses, preprocess, or postprocess configuration ATM.

Wrapping 64bit DLLs

So when trying to wrap a 64bit DLL the generator made the wrapper like this:

        [StructLayout(LayoutKind.Explicit, Size = 4)]
        public struct Internal
        {
           ...
        }

        int CppSharp.Runtime.ICppMarshal.NativeDataSize
        {
            get { return 4; }
        }

        public MyClass()
        {
            __Instance = Marshal.AllocHGlobal(4);
            Internal.MyClass_0(__Instance);
        }

Causing memory corruption when calling the 64bit library. Manually replacing all the '4's with '8's fixed it.

How do I define for my ILibrary that my DLL is 64bit?

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.