2015-04-29 40 views
0

我有一個問題,重用從VB 6.0到VB.NET使用的C++ DLL。從VB.NET調用非託管代碼C++ dll

我的一個隊友在VB6.0中編寫了一個代碼,用於調用在VC++ 6.0中編程的Ansi C++ DLL。

該函數聲明如下;

​​3210

在VB6.0前者代碼中調用此DLL這樣

status = IniciaGestion(Me.hWnd, "DRVCOMM2.ini", mensaerror) 

其中mensaerror是被定義爲

Public mensaerror As String * 256 

輸出參數現在,我可以使用從VB這個DLL 。淨?

我有這個第三個參數的聲明有問題。
我使用這個聲明

<DllImport("GestionPrg.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Ansi)> _ 
Public Shared Function IniciaGestion(<MarshalAs(UnmanagedType.I4)> ByVal a As Integer, <MarshalAs(UnmanagedType.LPStr)> ByVal b As String, <OutAttribute(), MarshalAs(UnmanagedType.LPTStr)> ByRef c As String) As Long 

,並調用函數如下

Dim mensaerror As String 

Class1.IniciaGestion(Me.Handle, "C:\\Windows\\DRVCOMM2.ini", mensaerror) 

我調試和函數被調用,但是當我去分配價值mensaerror在C++代碼產生一個例外。

任何人都可以幫助我在VB.NET中的聲明?

回答

0

請在你的代碼前使用4個空格 - 使得它更容易閱讀...

<System.Runtime.InteropServices.DllImport("YourDLL.dll")> _ 
Public Shared Function IniciaGestion(ByVal a As IntPtr, ByRef b As String, ByRef c As String) As Long 
End Function 

Private Sub CallCode() 
    Dim mensaerror As String = "" 
    IniciaGestion(Me.Handle, "C:\Windows\DRVCOMM2.ini", mensaerror) 
End Sub 

應該做的工作......

+0

,除非你真的知道你在做什麼,當調用VB中的外部庫時,你永遠不會聲明字符串「ByRef」。 – GSerg

-1
Public Declare Ansi Function IniciaGestion Lib "GestionPrg.dll" (ByVal a As IntPtr, ByVal b As String, ByVal c As String) As Integer 

而且不要忘記在撥打電話前爲c分配空間,例如通過做

Dim mensaerror As String = Space(256) 

這樣做的更多的.NET的方法是使用一個StringBuilder雖然:

Public Declare Ansi Function IniciaGestion Lib "GestionPrg.dll" (ByVal a As IntPtr, ByVal b As String, ByVal c As StringBuilder) As Integer 

爲您調用之前設置所需的能力:

Dim mensaerror = New StringBuilder(256) 
+0

'更多的.NET方式'是*不*使用'聲明' - 使用'DllImport'屬性。 '聲明'僅在VB中與VB6向後兼容。 –

+0

你有點錯過了主要觀點,但是,這可以說是更多的.NET。話雖如此,'Declare'當然不僅僅是爲了向後兼容,因爲他們添加了原來VB中沒有的'Ansi/Unicode/Auto'功能,並且它們[不提](https:/ /msdn.microsoft.com/en-us/library/4zey12w5.aspx)不建議或不推薦使用它,就像它們爲[僅實際向後兼容的東西](https://msdn.microsoft.com/zh-cn/我們/庫/ microsoft.visualbasic.compatibility.vb6(v = vs.110)的.aspx)。 – GSerg

+0

您給出的鏈接('實際向後兼容性...')僅僅是關於VB6命名空間。 '聲明'是VB6語法,而不是VB6命名空間問題。 –