【问题标题】:Using delegates in C# as callback for C DllImported functions在 C# 中使用委托作为 C DllImported 函数的回调
【发布时间】:2011-08-02 09:01:20
【问题描述】:

我正在尝试调用 C DLL 的函数。

但我得到了 StackOverflowException,所以我认为函数作为参数有问题。

具体看起来像这样。

C DLL(头文件):

typedef struct
{
  MyType aType;     /* message type */
  int nItems;       /* number of items */
   const MyItems    *lpItem;    /* pointer to array of items */
} MyStruct;

typedef void (__stdcall *MyCbFunc) (HWND, const MyStruct  *);

API(BOOL) RegisterCbFunc (ARGS, MyCbFunc);

在 C# 中我试过这个:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct MyStruct
{
  MyType aType;
  int nItems;
  MyItems[] lpItem;
}

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void CallbackDelegate(MyStruct mStruct);

[DllImport("MY.dll", CallingConvention=CallingConvention.StdCall)]
private static extern int RegisterCbFunc(IntPtr hWnd, Delegate pCB);

public static void MyCbFunc(MyStruct mStruct)
{
  // do something
}

static void Main(string[] args)
{
  CallbackDelegate dCbFunc = new CallbackDelegate(MyCbFunc);
  int returnValue = RegisterCbFunc(IntPtr.Zero, dCbFunc);
  // here, returnValue is 1
}

这会一直运行,直到 DLL 调用回调函数。然后我得到一个错误:

An unhandled exception of type 'System.StackOverflowException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll

感谢您的帮助。

回答: 我不知道为什么,但是有一个答案现在被删除了?!

我试图恢复它。解决方案是对函数参数使用按引用调用而不是按值调用。

public delegate void CallbackDelegate(ref MyStruct mStruct);

【问题讨论】:

    标签: c# c delegates callback dllimport


    【解决方案1】:

    您的 C 函数需要一个指向 MyStruct 的指针,但您告诉 C# 它需要一个指向函数的指针。函数和结构之间的区别是......显着。也许尝试类似

    [DllImport("MY.dll", CallingConvention=CallingConvention.StdCall)] 私有静态外部 int RegisterCbFunc(IntPtr hWnd, Delegate PCB); 静态无效主要(字符串 [] 参数) { 我的结构 mStruct; int returnValue = RegisterCbFunc(IntPtr.Zero, mStruct); }

    如果你的 C 函数用它自己分配的东西填充 MyStruct 的 lpItem 成员,我不知道接下来会发生什么,但至少它不会试图覆盖你的代码。

    【讨论】:

    • 抱歉。我忘记了头文件中 RegisterCbFunc 的声明。它看起来像这样:API(BOOL) RegisterCbFunc (ARGS, MyCbFunc);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2013-10-10
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多