Created
May 2, 2019 10:17
-
-
Save raizam/0f244e52066cd6a875c204a82b57f192 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
namespace SharpC | |
{ | |
partial struct CharPtr | |
{ | |
public CharPtr(IntPtr ptr) => this.Ptr = ptr; | |
IntPtr Ptr { get; } | |
//public static implicit operator CharPtr(ReadOnlySpan<char> d) => d.ptr != 0; | |
// public static implicit operator CBool(bool b) => new CBool { val = (b ? 1 : 0) }; | |
} | |
partial struct CBool | |
{ | |
int val; | |
public static implicit operator bool(CBool d) => d.val != 0; | |
public static implicit operator CBool(bool b) => new CBool { val = (b ? 1 : 0) }; | |
} | |
internal unsafe static class CStringExtensions | |
{ | |
public static CString ToAnsii(this string val) => ToAnsii(val.AsSpan()); | |
public static CString ToAnsii(this ReadOnlySpan<char> val) | |
{ | |
var buffSize = val.Length * 2; | |
var ptr = Marshal.AllocHGlobal(buffSize); | |
var span = new Span<byte>((void*)ptr, buffSize); | |
var len = Encoding.ASCII.GetBytes(val, span); | |
return new CString { Ptr = (ptr), Length = (uint)len }; | |
} | |
} | |
internal struct CString : IDisposable | |
{ | |
public static implicit operator CharPtr(CString d) => new CharPtr(d.Ptr); | |
public IntPtr Ptr { get; internal set; } | |
public uint Length { get; internal set; } | |
public void Dispose() | |
{ | |
Marshal.FreeHGlobal(Ptr); | |
} | |
} | |
public static class SharpC | |
{ | |
public static T Alloc<T>(T defaultVal = default) where T : unmanaged | |
{ | |
return new T(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment