Meh*_*dad 5 .net c# generics cdecl variadic-functions
为什么Foo()成功但却Bar()抛出了BadImageFormatException?
using System.Runtime.InteropServices;
using System.Text;
static class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int sprintf([Out] StringBuilder buf, string format, __arglist);
static void Main(string[] args)
{
Foo<int>(2); //Runs fine
Bar<int>(2); //Error: "The signature is incorrect"
}
static void Foo<T>(int a) { sprintf(new StringBuilder(8), "%d", __arglist(a)); }
static void Bar<T>(T a) { sprintf(new StringBuilder(8), "%d", __arglist(a)); }
}
Run Code Online (Sandbox Code Playgroud)
尝试这样:
using System;
using System.Runtime.InteropServices;
using System.Text;
static class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int sprintf([Out] StringBuilder buf, string format, params object[] args);
static void Main(string[] args)
{
Foo(2);
Bar<int>(2);
}
static void Foo(int a) { sprintf(new StringBuilder(8), "%d", a); }
static void Bar<T>(T a){ sprintf(new StringBuilder(8), "%d", a); }
}
Run Code Online (Sandbox Code Playgroud)