2011-08-02 8 views
0

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); 

答えて

1

あなたのC関数はMyStructへのポインタを期待していますが、C#に関数へのポインタが必要だと伝えています。関数と構造体の違いは...重要です。おそらく、あなたのC関数は、それ自体を割り当て何かを体mystructのlpItemメンバーに充填されている場合は、私が次に何が起こるか全くわから得なかっましたが、少なくともそれはしようとすることはないだろう

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

static void Main(string[] args) 
{ 
MyStruct mStruct; 
int returnValue = RegisterCbFunc(IntPtr.Zero, mStruct); 
} 

のようなものを試してみてくださいコードを上書きします。

+0

申し訳ありません。私は、ヘッダーファイルにRegisterCbFuncの宣言を忘れていました。次のようになります。API(BOOL)RegisterCbFunc(ARGS、MyCbFunc); – Catscratch

関連する問題