static unsafe string FormatPrintF(string format, object arg)
{
// Determine how much space is needed to store the formatted string.
string stringArg = arg as string;
int neededLength = stringArg != null ?
snprintf(null, IntPtr.Zero, format, stringArg) :
snprintf(null, IntPtr.Zero, format, (int)arg);
if (neededLength == 0)
return string.Empty;
if (neededLength < 0)
throw new InvalidOperationException("The printf operation failed");
// Allocate the needed space, format into it, and return the data as a string.
byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator
fixed (byte* ptr = bytes){
int length = stringArg != null ?
snprintf(ptr, (IntPtr)bytes.Length, format, stringArg) :
snprintf(ptr, (IntPtr)bytes.Length, format, (int)arg);
if (length != neededLength)
{
throw new InvalidOperationException("Invalid printf operation");
}
}
return StringFromAsciiBytes(bytes, 0, neededLength);
}