I'm trying to call string.FastAllocateString directly from my code. (Actually, I'm trying to avoid unnecesary memory copies when creating a string from a char* - if there's a better way, I'd love to know.)
This is my code:
Code Block
var
fas =newDynamicMethod("", typeof(string), new[] { typeof(int) });var
fasMethod =typeof(string).GetMethod("FastAllocateString", BindingFlags.NonPublic |BindingFlags.Static);var
ilGen = fas.GetILGenerator();ilGen
.Emit(OpCodes.Ldarg_0);ilGen
.Emit(OpCodes.Call, fasMethod);ilGen
.Emit(OpCodes.Ret);Func
<int, string> FastAllocateString = (Func<int, string>)fas.CreateDelegate(typeof(Func<int, string>));FastAllocateString(10);
The IL is fine, but when I make the call, I get:
System.MethodAccessException: System.String.FastAllocateString(Int32)
at (Int32 )
at System.StringExtensions..cctor() in C:\mycode.cs:line 96
What am I missing?