代码之家  ›  专栏  ›  技术社区  ›  Noldor130884

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

  •  0
  • Noldor130884  · 技术社区  · 7 年前

    我正在用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
    

    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();
    }
    

    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 使我的代码在没有任何错误的情况下崩溃(the MainMenu

    我用相同的声明在另一个VB环境(Excel)上尝试了DLL。

    Private Declare Function Version_Get Lib "mypath/mydll.dll" () As String
    

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

    我做错了什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Noldor130884    6 年前

    我必须创建一个类,通过封送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