2012-05-03 10 views
2

私はです.C++私はC#で呼び出す関数をいくつか持っています。機能の一つがこれです:ヒープやロードされたDLLの破損により、Windowsがブレークポイントを引き起こしました

char segexpc[MAX_SEG_LEN]; 

extern "C" QUERYSEGMENTATION_API char* fnsegc2Exported() 
{ 
    return segexpc2; 
} 

は、どこかのプログラムでは、私もこの事をやっている:私のC#プログラムで

if(cr1==1) 
{ 
strcpy(segexpc, seg); 
} 

、私はfollowign方法によって上記を起動しています:

[DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] 
public static extern StringBuilder fnsegcExported(); 

this.stringbuildervar = fnsegcExported();

これまで私は何のエラーも出ていませんでしたが、今私はVisual Studioでデバッグすると突然このエラーが発生し始めました。

Windows has triggered a breakpoint in SampleAppGUI.exe. 
This may be due to a corruption of the heap, which indicates a bug in SampleAppGUI.exe or any of the DLLs it has loaded. 
This may also be due to the user pressing F12 while SampleAppGUI.exe has focus. 

このエラーは、ウィンドウを表示する直前に表示されます。私はF12キーを押していませんし、ブレークポイントもここには設定されていませんが、この時点でエラーが発生している理由はわかりません。 this.stringbuildervar = fnsegcExported();
[続行]を押すと、ウィンドウに正しい出力が表示されます。

答えて

1

this.stringbuildervar = new StringBuilder(fnsegcExported()); 

stringは、より適切と思われますタイプ。または、Marshalクラスを使用して、管理されていないchar *を管理された文字列にマーシャリングすることをお勧めします。

[DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] 
public static extern IntPtr fnsegcExported(); 

string managedStr = Marshal.PtrToStringAnsi(fnsegcExported); 
this.stringbuildervar = new StringBuilder(managedStr); 
0

この行でエラーが表示される理由は、デバッグ情報がある最後のスタックフレームであるためです。

あなたのケースでは、C++側にはほとんどコードがありません。 segexpcにゼロ終端文字列が含まれていることを確認してください。

文字列ビルダーの既定の容量が16であるため、この方法で長い文字列を返すことができない可能性があります。たぶんあなたはただの文字列を返したいでしょう。

あなたのC++文字列が非Unicodeである必要があるかどうかも疑問です。それはすべての変換時にパフォーマンスを傷つけるでしょう。あなたは

[DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] 
public static extern string fnsegcExported(); 

[DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] 
public static extern StringBuilder fnsegcExported(); 

から外部宣言を変更し、次の方法でそれを呼び出した場合に何が起こるか

+0

@jarika:私は完全にC++に精通していませんが、strcpyが '\ 0'までコピーするかどうかは疑問でした。そうでなければ、自動的にコピーして宛先文字列をヌル終了文字列にするC++の関数もありますか? – user1372448

+0

strcpyはヌルターミネーターをあなたのために追加します(\ 0) 'ソースによってポイントされたC文字列を、終端ヌル文字を含む宛先によって指された配列にコピーします。 –

関連する問題