2013-10-18 40 views
1

我創建了非託管dll並在VB.Net中使用。在VB.Net中使用C++ dll時出現異常

這兩個代碼snippiest如下。

VB.Net

Imports System.Text 
Imports System.Runtime.InteropServices 

Module Module1 

    Sub Main() 
     Dim c As cls = New cls() 
     c.Start() 
    End Sub 

End Module 

Public Class cls 
    Declare Sub Only Lib "dllproj2.dll" Alias "Only" (b As StringBuilder) 

    Public Sub Start() 
     Dim s As StringBuilder = New StringBuilder(15) 

     Only(s) '**Actual call to dll code ** 
     Dim s1 As String = s.ToString.ToLower 
     Dim len As Integer = s.ToString.Length.ToString() 
     Console.Write(s.ToString()) 
    End Sub 

End Class 

C++ DLL

#include<stdio.h> 
#include<stdlib.h> 
#include<cstring> 

extern "C"{ 
void Only(char *a) 
{ 
    char arr[10]; 

    printf("Reached"); 
    sprintf(arr,"This %d",33); 
    printf("\n%s\n",arr); 
    memcpy(a,arr,10); 

} 
} 

現在只要我訪問線Only(s)我得到的圖像顯示異常。

enter image description here

我無法理解異常原因。代碼的輸出很好,但使用Visual Studio 2012 Express運行時,它會出現上述錯誤。

這是我們在生產中也使用過的示例代碼,恐怕以後可能會引起問題。

請建議有什麼辦法擺脫異常。

謝謝。

回答

1

您必須聲明b爲:UnmanagedType.LPStr

Declare Sub Only Lib "dllproj2.dll" Alias "Only" (<InAttribute(), MarshalAs(UnmanagedType.LPStr)> b As StringBuilder) 
+0

但b爲得到修改C++代碼,所以InAttribute()是OK?我試過建議,仍然會得到相同的異常。 –

+0

InAttribute表示數據應該從調用者到被調用者編組,但不返回給調用者。 –

+0

好吧,我明白了,但是當我使用建議的代碼時,我仍然得到異常。 –

相關問題