我正在Visual Studio 2013中用VB.NET编写一个小应用程序,到目前为止我写的是以下代码:
Public Class MainMenu
Private Declare Function Version_Get Lib "mypath/mydll.dll" () As String
' Before anyone asks, yes, the DLL is present in the mypath folder
Private Sub MainMenu_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim Temp As String
Dim Dummy As Integer
On Error GoTo Handler
Temp = Version_Get
Dummy = 1 ' This line is never reached in debug mode
Handler:
If Not IsNothing(Err.GetException()) Then
MsgBox("Error " & Str(Err.Number) & " generated by the application " & Err.Source & ControlChars.CrLf & Err.Description, vbCritical, "Error")
End
End If
End Sub
End Class
DLL应该返回BSTR
(当然这是extern "C"
等等,但为了理解我正在编写纯粹而简单的函数):
档案.h
#ifdef EVALFUNC_EXPORTS
#define EVALFUNC_API __declspec(dllexport)
#else
#define EVALFUNC_API __declspec(dllimport)
#endif
extern "C"
{
EVALFUNC_API BSTR __stdcall Version_Get();
}
档案.cpp
BSTR __stdcall Version_Get()
{
CRegKey Key;
CString sValue;
BSTR Str;
LONG nA = Key.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\my Software"), KEY_READ);
// Before anyone asks, yes, the application is present in the system
ULONG nValueLength = 0;
LONG nB = Key.QueryStringValue(_T("Version"), NULL, &nValueLength);
if (nValueLength > 0) LONG nC = Key.QueryStringValue(_T("Version"), sValue.GetBufferSetLength(nValueLength - 1), &nValueLength);
Str = sValue.AllocSysString();
return Str;
}
问题在于,即使我编写了错误处理程序,代码也不会遇到错误,Version_Get
会导致代码崩溃而不会出现任何错误(无论如何都会加载MainMenu
表单。)
我在另一个VB环境(Excel)上使用相同的声明尝试了DLL。
Private Declare Function Version_Get Lib "mypath/mydll.dll" () As String
在这种情况下,字符串变量用正确的文本填充。
我做错了什么?
答案 0 :(得分:0)
我必须通过编组BSTR字符串来创建一个导入Dll的类:
Imports System.Runtime.InteropServices
Public Class ImportDll
<DllImport("myDll.dll", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function Version_Get() As <MarshalAs(UnmanagedType.BStr)> String
End Function
End Class
可以按如下方式调用代码:
Version = ImportDll.Version_Get