c# - 在 C# 中调用 UnmanagedFunctionPointer 以实现自定义调用约定

标签 c# pinvoke function-pointers unsafe

我在 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/

相关文章:

c++ - 无法使用函数指针调用函数

c - 在 C 中初始化包含函数指针的结构

c# - C#-将* .wav文件加载到字节数组时伪造数据

c++ - 在 VB.NET 中使用 DLL 导入/声明以及 .NET 不使用的参数类型

c# - P/Invoke ioctl 系统调用

c++ - 创建 __stdcall 的映射

c# - 以编程方式使用 jira 的最佳方法

c# - VStudio 2019 中缺少 “Merge changes in merge tool” 、 “Take server version” 等按钮

c# - C#中如何等待点击

C# P/Invoke on CUDA DLL 最终导致 AccessViolationException