2

C# で呼び出しているいくつかのエクスポートされた関数を含むC ++ファイルがあります。関数の1つはこれです:

char segexpc[MAX_SEG_LEN];

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

プログラムのどこかで、次のことも行っています。

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

私のC#プログラムでは、次の方法で上記を呼び出しています。

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

this.stringbuildervar = fnsegcExported();

以前はエラーが発生しませんでしたが、ビジュアルスタジオでデバッグすると、突然このエラーが発生し始めました。

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();
続行を押すと、ウィンドウに正しい出力が表示されます。

4

2 に答える 2

1

外部宣言を

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

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

そして、次の方法で呼び出します。

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);
于 2012-05-03T14:42:05.263 に答える
0

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

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

文字列ビルダーのデフォルトの容量は 16 であるため、この方法ではより長い文字列を返すことができない可能性があると思います。文字列だけを返したいと思うかもしれません。

また、C++ 文字列を非 Unicode にする必要があるかどうかも疑問です。これにより、変換のたびにパフォーマンスが低下します。

于 2012-05-03T13:16:36.863 に答える