【发布时间】: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