DLL 未在 visual studio 2013 VB 代码中导出字符串

DLL not exporting string in visual studio 2013 VB code

我在 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 应该 return 一个 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

在这种情况下,字符串变量会填入正确的文本。

我做错了什么?

我必须创建一个 class 来通过编组 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