Visual Basic WPF 加载 ATL C++ dll 程序在返回 String 类型时退出

问题描述

我正在使用 VB.net WPF 和 dll 用 ATL 制作这个项目 但是每次我运行dll函数时,程序都没有错误退出 请告诉我为什么不起作用以及如何解决它。

c++ 函数

extern "C" __declspec(dllexport) BSTR __cdecl sprint(LPSTR str1,LPSTR str2) {
    TCHAR test[100];
    sprintf_s(test,100,"%s %s",str1,str2);

    BSTR test2 = L"helloworld";
    return test2;
}

VB.net 代码

声明

    <DllImport("database.dll",CallingConvention:=CallingConvention.Cdecl)>
    Private Shared Function sprint(ByVal str1 As String,ByVal str2 As String) As String
    End Function

使用

    Private Sub On_Submit_Btn_Clk(sender As Object,e As RoutedEventArgs)
        testStr = sprint("hello","world")
        MessageBox.Show(testStr)
    End Sub

问题:

调用函数“sprint”时程序退出

没问题:

函数“sprint”返回整数时程序不退出

只有 BSTR,LPTSTR,LPSTR 类型返回 make proram exit.

解决方法

在 COM 编程中,BSTR 是一个特殊的 LPWSTR,由 SysAllocString 分配,由 SysFreeString 释放。字符前面是字符串长度,偏移量为 -1。这意味着您可以将 BSTR 传递给所有需要 LPCWSTR

L"helloworld" 是一个 C++ 文字,它几乎匹配 LPWSTR 类型,除了 const 部分。而 VC++ 将掩盖最后一个小问题。 MSVC 中最简单的解决方案是对 _bstr_t 使用 BSTR 包装器类型,它为您执行 SysAllocString。否则,您需要手动执行此操作。