bflattened / bflat

C# as you know it but with Go-inspired tooling (small, selfcontained, and native executables)
GNU Affero General Public License v3.0
3.56k stars 102 forks source link

[zerolib] can you give a printf combined with an example of printing string (including Chinese) Thank #141

Closed ghost closed 5 months ago

ghost commented 5 months ago

`using System; using System.Runtime.InteropServices;

var start = GetTickCount64(); xxxx var end = GetTickCount64();

printf("耗时: %d\n", end - start); ????

[DllImport("api-ms-win-core-sysinfo-l1-1-0")] static extern long GetTickCount64();

[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)] static extern int printf(string format, long value); ` compiled output:

E:\ConsoleApp4\ConsoleApp4>C:\Users\Administrator\Downloads\bflat-8.0.1-windows-x64\bflat.exe build -Os --stdlib Zero Error: AggregateException_ctor_DefaultMessage (Code generation failed for method '[ConsoleApp4]Program.<<Main>$>g__printf|0_4(string,int64)') System.AggregateException: AggregateException_ctor_DefaultMessage (Code generation failed for method '[ConsoleApp4]Program.<<Main>$>g__printf|0_4(string,int64)') ---> ILCompiler.CodeGenerationFailedException: Code generation failed for method '[ConsoleApp4]Program.<<Main>$>g__printf|0_4(string,int64)' ---> System.InvalidOperationException: Expected method 'StringToAnsiString' not found on type '[zerolib]Internal.Runtime.CompilerHelpers.InteropHelpers' at Internal.IL.HelperExtensions.GetKnownMethod(TypeDesc, String, MethodSignature) + 0x5d

MichalStrehovsky commented 5 months ago

You cannot use string in the pinvoke declaration. That requires marshalling the managed type into unmanaged representation. Use char*. Then invoke an API that accepts utf-16 (wprintf?). Printf does not.

ghost commented 5 months ago

Thanks for the reply, I was wondering if there was an easy way for [zerolib] to convert utf-16 to asni and then call a function like Printf

MichalStrehovsky commented 5 months ago

If you're on Windows, can you use WriteConsole instead of printf? It's better to just stick to UTF-16 on Windows (or UTF-8 on Linux with the "utf 8 literals added to the language recently"u8)

Otherwise you could use WideCharToMultiByte or some libc equivalent of that.

ghost commented 5 months ago

Ok thanks, I'll be using WideCharToMultiByte