我在 DLL 中有一个函数:
char __usercall MyUserCallFunction<al>(int arg1<esi>)
因为我讨厌自己,所以我想在 C# 中使用 P/Invoke 调用它。
通常这可以通过获取函数委托(delegate)来完成,a la:
[UnmanagedFunctionPointer(CallingConvention.ThisCall, CharSet = CharSet.Auto, SetLastError = true)]
public delegate char DMyUserCallFunction(IntPtr a1);
然后通过以下方式调用它:
var MyFunctionPointer = (DMyUserCallFunction)Marshal.GetDelegateForFunctionPointer(AddressOfFunction, typeof(DMyUserCallFunction));
MyFunctionPointer(IntPtr.Zero);
然而,对于自定义用户调用约定,这将导致程序崩溃。有没有什么方法可以使用不安全的代码或某种包装函数来执行此操作,这些函数可以将委托(delegate)放在适当的位置,但又不会强制我编写 C++ DLL?
谢谢!
编辑:
根据 dtb 的建议,我创建了一个非常小的 C++ DLL,我通过 P/Invoke 使用它来调用该函数。对于任何好奇 C++ 中的函数最终看起来像这样的人:
extern "C" __declspec(dllexport) int __stdcall callUsercallFunction(int functionPointer, int arg1 )
{
int retVal;
_asm
{
mov esi, arg1
call functionPointer
mov retVal, eax
}
//Fake returning al, the lower byte of eax
return retVal & 0x000000FF;
}
最佳答案
在 C# 中实现自定义调用约定是没有希望的。您必须在 native DLL 或 C++/CLI DLL 中执行此操作。
关于c# - 在 C# 中调用 UnmanagedFunctionPointer 以实现自定义调用约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7536484/