Skip to content

Instantly share code, notes, and snippets.

@rkttu
Created November 15, 2023 05:31
Show Gist options
  • Save rkttu/addc27b20f0a9d55c0cbbeac67baf667 to your computer and use it in GitHub Desktop.
Save rkttu/addc27b20f0a9d55c0cbbeac67baf667 to your computer and use it in GitHub Desktop.
macOS wchar_t P/Invoke Sample
// Require unsafe configuration.
using System.Runtime.InteropServices;
using System.Text;
namespace HelloWorld;
internal partial class NativeMethods
{
// https://github.com/mono/mono/issues/9362
static Encoding GetSystemUnicodeEncoding()
=> Environment.OSVersion.Platform == PlatformID.Unix ? Encoding.UTF32 : Encoding.Unicode;
public static byte[] ConvertToWideByteArray(string s)
=> GetSystemUnicodeEncoding().GetBytes(s);
private const string StandardLibraryMacOs = "libSystem.dylib";
[DllImport(StandardLibraryMacOs,
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.None,
ExactSpelling = true,
EntryPoint = nameof(wprintf))]
internal static extern int wprintf(
byte[] fmt);
[DllImport(StandardLibraryMacOs,
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.None,
ExactSpelling = true,
EntryPoint = nameof(wprintf))]
internal static extern int wprintf(
byte[] fmt,
int arg0);
[DllImport(StandardLibraryMacOs,
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.None,
ExactSpelling = true,
EntryPoint = nameof(wprintf))]
internal static extern int wprintf(
byte[] fmt,
int arg0, int arg1);
}
static unsafe class Program
{
static void Main(string[] args)
{
const int nLength = 5;
int* pContent = stackalloc int[nLength];
int nResult = 0;
for (int i = 0; i < nLength; i++)
*(pContent + i) = i;
nResult = NativeMethods.wprintf(
NativeMethods.ConvertToWideByteArray("Printing %d numbers.\n"),
nLength);
NativeMethods.wprintf(
NativeMethods.ConvertToWideByteArray("- Result: %d\n"),
nResult);
for (int i = 0; i < nLength; i++)
{
nResult = NativeMethods.wprintf(
NativeMethods.ConvertToWideByteArray("Index %d: Value %d\n"),
i, pContent[i]);
NativeMethods.wprintf(
NativeMethods.ConvertToWideByteArray("- Result: %d\n"),
nResult);
}
nResult = NativeMethods.wprintf(
NativeMethods.ConvertToWideByteArray("Done.\n"));
NativeMethods.wprintf(
NativeMethods.ConvertToWideByteArray("- Result: %d\n"),
nResult);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment