Nice things which you can't do in C++ but can in C# Native

Coordinator
Jan 20, 2015 at 9:22 AM
Edited Jan 20, 2015 at 9:25 AM
Hi Guys. I just want to show one code which can't be reproduced in C++ but can be done in C# Native
using System;

namespace ClassLibrary1
{
    using System.Text;

    public interface ITest
    {
        string GetString<T>(T t);
    }

    public class TestInt : ITest
    {
        public string GetString<T>(T t)
        {
            return t.ToString();
        }
    }

    public class Class1
    {
        public static void Test(ITest t)
        {
            var s1 = t.GetString(10);
            var s2 = t.GetString(20.0);
            var s3 = t.GetString("test");

            Console.WriteLine(s1);
            Console.WriteLine(s2);
            Console.WriteLine(s3);
        }

        public static int Main(string[] args)
        {
            ITest t = (ITest)new TestInt();

            Test(t);

            return 0;
        }
    }
}

Output
10
20
test
As you know C++ does not support templates for virtual members, C# .NET using dynamic functionality to generate methods and only C# Native compiles it into static code.
Jan 20, 2015 at 12:23 PM
I'm trying to setup emscripten support, i have this function:

[MethodImplAttribute(MethodImplOptions.Unmanaged)]
    public static extern unsafe void emscripten_run_script(char* str);

    private static void RunScript(String str)
    {
        unsafe
    {
                fixed (char* pc = &str.ToCharArray()[0])
                {
                    emscripten_run_script(pc);
                }
            }
    }
Would be possible to marshal the string to normal const char* ?
Add something like PInvoke string ansi etc would work.
Jan 20, 2015 at 12:31 PM
same goes everywhere in emscripten usage, for example fopen fails as the string is invalid in input, need to have some sort of parameter telling the string format to marshal to native.
Coordinator
Jan 20, 2015 at 1:55 PM
Edited Jan 20, 2015 at 1:56 PM
As I remember emscripten using 4 bytes per char. so you need to convert it into UTF32 before sending it as a native string

if you need to send ANSI string (which is 1 byte per char) then you need to convert it to Ansi before
        public static extern unsafe void emscripten_run_script(byte* str);

        private static void RunScript(String str)
        {
            unsafe
            {
                var bytes = Encoding.ASCII.GetBytes(str);
                fixed (byte* pc = bytes)
                {
                    emscripten_run_script(pc);
                }
            }
        }
and just make sure it ends with '\0'
Jan 20, 2015 at 6:27 PM
This does not work, how can i make sure it ends with '\0' ?
Modify the byte* pc value?
Coordinator
Jan 20, 2015 at 7:50 PM
try this

replace Encoding.ASCII.GetBytes(str) with Encoding.UTF32.GetBytes(str + "\0")