2012-05-03 44 views
2

我有一個C++文件,這是我在C#我打電話一些導出的函數。上述功能之一是這樣的:Windows已經引發了斷點由於堆損壞或DLL加載

char segexpc[MAX_SEG_LEN]; 

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

程序中某個位置,我也是做這件事:

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

在我C#程序,我調用上述由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

如果從

[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類將非託管字符*返回編組爲一個託管字符串。

[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。這將損害每次轉換的表現。

+0

@jarika:我不完全熟悉C++,但我想知道,如果strcpy副本,直到「\ 0」。如果沒有,C++中是否有任何函數會自動複製目標字符串並將其作爲空字符串結束? – user1372448

+0

strcpy將爲您添加空終止符(\ 0) '將由source指向的C字符串複製到目標指向的數組中,包括終止空字符' –