Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for wchar_t and std::wstring for C# #983

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build/Tests.lua
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ function SetupTestProjectsCLI(name, extraFiles, suffix)
dependson { name .. ".Native" }

LinkNUnit()
links { "CppSharp.Runtime" }
end

function IncludeExamples()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@ template __declspec(dllexport) std::basic_string<char, std::char_traits<char>, s
template __declspec(dllexport) std::basic_string<char, std::char_traits<char>, std::allocator<char>>::~basic_string() noexcept;
template __declspec(dllexport) std::basic_string<char, std::char_traits<char>, std::allocator<char>>& std::basic_string<char, std::char_traits<char>, std::allocator<char>>::assign(const char* const);
template __declspec(dllexport) const char* std::basic_string<char, std::char_traits<char>, std::allocator<char>>::data() const noexcept;

template __declspec(dllexport) std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>::basic_string(const wchar_t* const, const std::allocator<wchar_t>&);
template __declspec(dllexport) std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>::~basic_string() noexcept;
template __declspec(dllexport) const wchar_t* std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>::c_str() const noexcept;
template __declspec(dllexport) std::allocator<wchar_t>::allocator() noexcept;
133 changes: 117 additions & 16 deletions src/Generator/Generators/CSharp/CSharpMarshal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,10 @@ public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
supportBefore.WriteLineIndent($@"{value}[i] = {
Context.ReturnVarName}[i] != 0;");
else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{value}[i] = global::System.Convert.ToChar({
else if ((arrayType.IsPrimitiveType(PrimitiveType.Char) ||
arrayType.IsPrimitiveType(PrimitiveType.WideChar)) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{value}[i] = global::System.Convert.ToChar({
Context.ReturnVarName}[i]);");
else
supportBefore.WriteLineIndent($@"{value}[i] = {
Expand All @@ -119,7 +120,8 @@ public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
break;
case ArrayType.ArraySize.Incomplete:
// const char* and const char[] are the same so we can use a string
if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
if ((array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) ||
array.Type.Desugar().IsPrimitiveType(PrimitiveType.WideChar)) &&
array.QualifiedType.Qualifiers.IsConst)
{
var pointer = new PointerType { QualifiedPointee = array.QualifiedType };
Expand Down Expand Up @@ -215,6 +217,19 @@ public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write($"global::System.Convert.ToChar({Context.ReturnVarName})");
return true;
}
goto default;
case PrimitiveType.WideChar:
Context.Return.Write($"new CppSharp.Runtime.WideChar({Context.ReturnVarName})");
return true;
case PrimitiveType.Char16:
return false;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
Expand Down Expand Up @@ -268,11 +283,10 @@ public override bool VisitFunctionType(FunctionType function, TypeQualifiers qua
{
var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex;

Context.Before.WriteLine("var {0} = {1};", ptrName,
Context.ReturnVarName);
Context.Before.WriteLine($"var {ptrName} = {Context.ReturnVarName};");

Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
ptrName, function.ToString());
Context.Return.Write($@"({function.ToString()
})Marshal.GetDelegateForFunctionPointer({ptrName}, typeof({function.ToString()}))");
return true;
}

Expand All @@ -299,7 +313,7 @@ public override bool VisitClassDecl(Class @class)

public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("{0}", Context.ReturnVarName);
Context.Return.Write($"{Context.ReturnVarName}");
return true;
}

Expand All @@ -323,8 +337,7 @@ public override bool VisitParameterDecl(Parameter parameter)
if (!string.IsNullOrWhiteSpace(ctx.Return) &&
!parameter.Type.IsPrimitiveTypeConvertibleToRef())
{
Context.Before.WriteLine("var _{0} = {1};", parameter.Name,
ctx.Return);
Context.Before.WriteLine($"var _{parameter.Name} = {ctx.Return};");
}

Context.Return.Write("{0}{1}",
Expand Down Expand Up @@ -494,11 +507,17 @@ public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = (byte)({
Context.ArgName}[i] ? 1 : 0);");
else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = global::System.Convert.ToSByte({
Context.ArgName}[i]);");
else if ((arrayType.IsPrimitiveType(PrimitiveType.Char) ||
arrayType.IsPrimitiveType(PrimitiveType.WideChar)) &&
Context.Context.Options.MarshalCharAsManagedChar)
{
if(arrayType.IsPrimitiveType(PrimitiveType.Char))
supportBefore.WriteLineIndent(
$"{Context.ReturnVarName}[i] = global::System.Convert.ToSByte({Context.ArgName}[i]);");
else
supportBefore.WriteLineIndent(
$"{Context.ReturnVarName}[i] = global::System.Convert.ToChar({Context.ArgName}[i]);");
}
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = {
Context.ArgName}[i]{
Expand Down Expand Up @@ -632,14 +651,96 @@ public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
return true;
}

var marshalAsString = CSharpTypePrinter.IsConstCharString(pointer);
if (finalPointeeIsPrimitiveType || finalPointee.IsEnumType() ||
marshalAsString)
{
// From MSDN: "note that a ref or out parameter is classified as a moveable
// variable". This means we must create a local variable to hold the result
// and then assign this value to the parameter.

if (isRefParam)
{
var typeName = Type.TypePrinterDelegate(finalPointee);
if (Context.Function.OperatorKind == CXXOperatorKind.Subscript)
Context.Return.Write(param.Name);
else
{
if (param.IsInOut)
Context.Before.WriteLine($"{typeName} _{param.Name} = {param.Name};");
else
Context.Before.WriteLine($"{typeName} _{param.Name};");

Context.Return.Write($"&_{param.Name}");
}
}
else
{
if (!marshalAsString &&
Context.Context.Options.MarshalCharAsManagedChar &&
(primitive == PrimitiveType.Char || primitive == PrimitiveType.WideChar))
Context.Return.Write($"({typePrinter.PrintNative(pointer)}) ");

if (marshalAsString)
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name, primitive));
else
Context.Return.Write(Context.Parameter.Name);
}

return true;
}

return pointer.QualifiedPointee.Visit(this);
}

private string MarshalStringToUnmanaged(string varName, PrimitiveType type)
{
if (type == PrimitiveType.WideChar)
{
// Looks like Marshal.StringToHGlobalUni is already able
// to handle both Unicode and MBCS charsets
return $"Marshal.StringToHGlobalUni({varName})";
}

if (Equals(Context.Context.Options.Encoding, Encoding.ASCII))
return $"Marshal.StringToHGlobalAnsi({varName})";

if (Equals(Context.Context.Options.Encoding, Encoding.Unicode) ||
Equals(Context.Context.Options.Encoding, Encoding.BigEndianUnicode))
{
return $"Marshal.StringToHGlobalUni({varName})";
}
throw new NotSupportedException(
$"{Context.Context.Options.Encoding.EncodingName} is not supported yet.");
}

public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write("global::System.Convert.ToSByte({0})",
Context.Parameter.Name);
return true;
}
goto default;
case PrimitiveType.WideChar:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write("global::System.Convert.ToChar({0})",
Context.Parameter.Name);
return true;
}
goto default;
case PrimitiveType.Char16:
return false;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
Expand Down
11 changes: 9 additions & 2 deletions src/Generator/Generators/CSharp/CSharpTypePrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,10 @@ public static void GetPrimitiveTypeWidth(PrimitiveType primitive,
width = targetInfo?.CharWidth ?? 8;
signed = true;
break;
case PrimitiveType.WideChar:
width = targetInfo?.WCharWidth ?? 16;
signed = false;
break;
case PrimitiveType.UChar:
width = targetInfo?.CharWidth ?? 8;
signed = false;
Expand Down Expand Up @@ -482,8 +486,11 @@ public override TypePrinterResult VisitPrimitiveType(PrimitiveType primitive,
"byte" : "bool";
case PrimitiveType.Void: return "void";
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.WideChar: return "char";
case PrimitiveType.Char32: return "char";
case PrimitiveType.WideChar:
return (ContextKind == TypePrinterContextKind.Native)
? GetIntString(primitive, Context.TargetInfo)
: "CppSharp.Runtime.WideChar";
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
return Options.MarshalCharAsManagedChar &&
Expand Down
6 changes: 5 additions & 1 deletion src/Generator/Passes/CheckAbiParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ public override bool VisitFunctionDecl(Function function)

// Deleting destructors (default in v-table) accept an i32 bitfield as a
// second parameter in MS ABI.
if (method != null && method.IsDestructor && Context.ParserOptions.IsMicrosoftAbi)
var @class = method != null ? method.Namespace as Class : null;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needlessly complicated - if the method is not null, then its name-space is always a class, just cast it.

if (method != null &&
method.IsDestructor &&
@class.IsDynamic &&
Context.ParserOptions.IsMicrosoftAbi)
{
method.Parameters.Add(new Parameter
{
Expand Down
34 changes: 34 additions & 0 deletions src/Generator/Passes/IgnoreSystemDeclarationsPass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,40 @@ public override bool VisitClassDecl(Class @class)
switch (@class.Name)
{
case "basic_string":
foreach (var method in @class.Methods.Where(m => !m.IsDestructor && m.OriginalName != "c_str"))
method.ExplicitlyIgnore();
foreach (var basicString in GetCharSpecializations(@class))
{
basicString.GenerationKind = GenerationKind.Generate;
foreach (var method in basicString.Methods)
{
if (method.IsDestructor || method.OriginalName == "c_str" ||
(method.IsConstructor && method.Parameters.Count == 2 &&
(( method.Parameters[0].Type.Desugar().IsPointerToPrimitiveType(PrimitiveType.Char) &&
!method.Parameters[1].Type.Desugar().IsPrimitiveType()) ||
( method.Parameters[0].Type.Desugar().IsPointerToPrimitiveType(PrimitiveType.WideChar) &&
!method.Parameters[1].Type.Desugar().IsPrimitiveType()))))
{
if(method.OriginalName == "c_str")
{
if (basicString.Arguments[0].Type.Type.Desugar().IsPrimitiveType(PrimitiveType.WideChar))
method.Name = method.Name + "W";
else if(basicString.Arguments[0].Type.Type.Desugar().IsPrimitiveType(PrimitiveType.Char))
method.Name = method.Name + "A";
}

method.GenerationKind = GenerationKind.Generate;
method.Namespace.GenerationKind = GenerationKind.Generate;
method.InstantiatedFrom.GenerationKind = GenerationKind.Generate;
method.InstantiatedFrom.Namespace.GenerationKind = GenerationKind.Generate;
}
else
{
method.ExplicitlyIgnore();
}
}
}
break;
case "allocator":
case "char_traits":
@class.GenerationKind = GenerationKind.Generate;
Expand Down
21 changes: 17 additions & 4 deletions src/Generator/Types/Std/Stdlib.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,8 @@ public class ConstChar16TPointer : ConstCharPointer

[TypeMap("basic_string<char, char_traits<char>, allocator<char>>", GeneratorKind = GeneratorKind.CSharp)]
[TypeMap("basic_string<char, char_traits<char>, allocator<char>>", GeneratorKind = GeneratorKind.CLI)]
[TypeMap("basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t>>", GeneratorKind = GeneratorKind.CSharp)]
[TypeMap("basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t>>", GeneratorKind = GeneratorKind.CLI)]
public class String : TypeMap
{
public override Type CLISignatureType(TypePrinterContext ctx)
Expand All @@ -323,14 +325,24 @@ public override Type CLISignatureType(TypePrinterContext ctx)

public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.Parameter.Name);
var type = ctx.Parameter.Type.Desugar();
ClassTemplateSpecialization basicString = GetBasicString(type);

if(basicString.Arguments[0].Type.Type.IsPrimitiveType(PrimitiveType.Char))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A space after the conditional operator.

ctx.Return.Write($"clix::marshalString<clix::E_UTF8>({ctx.Parameter.Name})");
else
ctx.Return.Write($"clix::marshalString<clix::E_UTF16>({ctx.Parameter.Name})");
}

public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.ReturnVarName);
var type = ctx.ReturnType.Type.Desugar();
ClassTemplateSpecialization basicString = GetBasicString(type);

if (basicString.Arguments[0].Type.Type.IsPrimitiveType(PrimitiveType.Char))
ctx.Return.Write($"clix::marshalString<clix::E_UTF8>({ctx.ReturnVarName})");
else
ctx.Return.Write($"clix::marshalString<clix::E_UTF16>({ctx.ReturnVarName})");
}

public override Type CSharpSignatureType(TypePrinterContext ctx)
Expand Down Expand Up @@ -381,6 +393,7 @@ public override void CSharpMarshalToManaged(CSharpMarshalContext ctx)
ClassTemplateSpecialization basicString = GetBasicString(type);
var data = basicString.Methods.First(m => m.OriginalName == "data");
var typePrinter = new CSharpTypePrinter(ctx.Context);

string qualifiedBasicString = GetQualifiedBasicString(basicString);
string varBasicString = $"__basicStringRet{ctx.ParameterIndex}";
bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField ||
Expand Down
34 changes: 34 additions & 0 deletions src/Runtime/Helpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace CppSharp.Runtime
{
public static class Helpers
{
public static string MarshalEncodedString(IntPtr ptr, Encoding encoding)
{
if (ptr == IntPtr.Zero)
return null;

var size = 0;
while (Marshal.ReadInt32(ptr, size) != 0)
size += sizeof(int);

var buffer = new byte[size];
Marshal.Copy(ptr, buffer, 0, buffer.Length);

return encoding.GetString(buffer);
}

public static IntPtr StringToHGlobalMultiByteUni(string str)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't used anywhere.

{
byte[] bytes = Encoding.UTF8.GetBytes(str);

IntPtr nativePtr = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, nativePtr, bytes.Length);

return nativePtr;
}
}
}
Loading