C# 创建委托类型非泛型
我想通过将libraryname和functionname指定为字符串,将参数指定为普通类型params object[]参数来调用非托管函数。 函数GetDelegateForFunctionPointer需要非泛型委托类型,但Expression类的函数GetDelegateType提供泛型操作或Func委托。有人有办法解决这个问题吗 对不起,我的英语不好,这是我在学校最差的科目。C# 创建委托类型非泛型,c#,types,delegates,marshalling,C#,Types,Delegates,Marshalling,我想通过将libraryname和functionname指定为字符串,将参数指定为普通类型params object[]参数来调用非托管函数。 函数GetDelegateForFunctionPointer需要非泛型委托类型,但Expression类的函数GetDelegateType提供泛型操作或Func委托。有人有办法解决这个问题吗 对不起,我的英语不好,这是我在学校最差的科目。 提前非常感谢您的回答!: 为什么不使用MessageBox.Show?我想这只是一个例子。嗯。。。这是为我编写
提前非常感谢您的回答!: 为什么不使用MessageBox.Show?我想这只是一个例子。嗯。。。这是为我编写的。您得到了什么错误?这是一个运行时错误:指定的类型不能是泛型类型定义。我在运行时创建了一个委托,所以这当然可以完美地编译,问题是:我调用GetDelegateType,它创建了一个泛型委托类型,请参见Action和Func。问题是:是否有其他方法可以动态调用非托管函数?@PMF。如果要重现此问题,需要使用CharSet=CharSet.Ansi将DLLImport属性调整为[DllImportkernel32.dll,CharSet=CharSet.Ansi,SetLastError=true]
static void CallUnmanageFunction(string dllName, string functionName, params object[] parameters)
{
IntPtr dllHandle = LoadLibrary(dllName);
IntPtr functionHandle = GetProcAddress(dllHandle, functionName);
List<Type> typeParameters = new List<Type>();
foreach (object p in parameters)
{
typeParameters.Add(p.GetType());
}
Type type = Expression.GetDelegateType(typeParameters.ToArray());
Delegate function = Marshal.GetDelegateForFunctionPointer(functionHandle, type);
function.DynamicInvoke(parameters);
}
static void Main(string[] args)
{
CallUnmanageFunction("user32.dll", "MessageBoxA", IntPtr.Zero, "Es funktioniert", "Test", (uint)0);
}