CppSharp icon indicating copy to clipboard operation
CppSharp copied to clipboard

Add ability to map certain C++ types to predefined ones (eg. WinAPI's _GUID -> System.Guid)

Open baremetaldude opened this issue 9 years ago • 3 comments

Brief Description

Need ability to map _GUID type in fields/parameters type to C#'s System.Guid

OS: Windows / OS X / Linux (include version and/or distro)

Used headers

Stripped part of windows.h

Used settings

Target: MSVC/GCC/Clang

Other settings

Stack trace or incompilable generated code

baremetaldude avatar Aug 23 '17 14:08 baremetaldude

Hey @baremetaldude.

This is supported by using our type maps feature.

Unfortunately we don't have much documentation for this feature, but you can see here a simple example: https://github.com/mono/CppSharp/blob/09e568d0b3ef847d3f5eccd37dffa0052727f9ba/src/Generator/Types/Std/Stdlib.cs#L436

We'll gladly accept any PRs improving our built-in type maps to provide support for more pre-defined types, like those on WinAPI. Would you be interested in contributing?

tritao avatar Aug 23 '17 14:08 tritao

I tried TypeMap, it allows to rewrite marshalling sites, but I still miss ability to skip code generation for _GUID (need special flag, code for some special classes/structs may be generated by tool, then moved/rewritten by hand). Even if I remove it from declaration lists generated code still not clear while converting it to intptr's. Someone familar with CppSharp internals should check it against platform-specific libraries ( parts of WinApi, glib etc) since SDL didnt cover all typical cases

public void Preprocess( Driver driver, ASTContext ctx ) {
	driver.Context.TypeMaps.TypeMaps.Add( "_GUID", typeof( _GUID ) );

	foreach( var @class in ctx.FindClass( "_GUID" ) ) {
		@class.Type = ClassType.ValueType;
		@class.GenerationKind = GenerationKind.None;
	}

	{ var guid = ctx.FindClass( "_GUID" ).First(); guid.TranslationUnit.Declarations.Remove( guid ); }
	....
}

public class _GUID : TypeMap {
	public override bool DoesMarshalling => true;

	public override string CSharpSignature( TypePrinterContext ctx ) {
		return "global::System.Guid";
	}

	public override void CSharpMarshalToNative( CSharpMarshalContext ctx ) {
		ctx.Return.Write( ctx.Parameter.Name );
	}

	public override void CSharpMarshalToManaged( CSharpMarshalContext ctx ) {
		ctx.Return.Write( ctx.ReturnVarName );
	}
}

baremetaldude avatar Aug 24 '17 12:08 baremetaldude

Type maps provide an IsIgnored property that be set to true to ignore such types. Is this what you're looking for? If not, feel free to discuss it with me in Gitter so I can understand what you need.

About checking the output with other libraries, we'll gladly take concrete issue reports and see what we can do to improve the situation.

tritao avatar Aug 29 '17 20:08 tritao