C DLLの関数を呼び出そうとしています。C#の代理人をC DllImported関数のコールバックとして使用
私は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#の場合:これは限りDLLは、コールバック関数を呼び出すまで実行
[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
}
。次に、エラーが発生しました:
An unhandled exception of type 'System.StackOverflowException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
ありがとうございました。
回答: 理由はわかりませんが、回答は削除されましたか?
私はそれを回復しようとします。解決策は、関数パラメータの値による呼び出しの代わりに参照による呼び出しを使用することでした。
public delegate void CallbackDelegate(ref MyStruct mStruct);
申し訳ありません。私は、ヘッダーファイルにRegisterCbFuncの宣言を忘れていました。次のようになります。API(BOOL)RegisterCbFunc(ARGS、MyCbFunc); – Catscratch