简体   繁体   English

Visual basic WPF 加载 ATL C++ dll 程序退出时返回字符串类型

[英]Visual basic WPF load ATL C++ dll program exit when return String type

I'm using VB.net WPF with dll made with ATL for this project but every time I run dll function, program exit with no error please let me know why is not working and how to fix it. I'm using VB.net WPF with dll made with ATL for this project but every time I run dll function, program exit with no error please let me know why is not working and how to fix it.

c++ function c++ function

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 code VB.net代码

declaration宣言

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

usage用法

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

issue:问题:

program exit when function "sprint" called.当 function “sprint”被调用时程序退出。

no issue:没有任何问题:

program not exit when function "sprint" return integer.当 function “sprint” 返回 integer 时程序不退出。

only BSTR, LPTSTR, LPSTR type returns make proram exit.只有 BSTR、LPTSTR、LPSTR 类型返回使 proram 退出。

In COM programming, a BSTR is a special LPWSTR which is allocated by SysAllocString , freed by SysFreeString .在 COM 编程中, BSTR是一个特殊的LPWSTR ,由SysAllocString分配,由SysFreeString释放。 The characters are preceded by the string length, at offset -1.字符前面是字符串长度,偏移量 -1。 That means you can pass a BSTR to all functions that expect an LPCWSTR这意味着您可以将BSTR传递给所有需要LPCWSTR的函数

L"helloworld" is a C++ literal, which happens to almost match the LPWSTR type, except for the const part. L"helloworld"是一个 C++ 文字,它恰好与LPWSTR类型几乎匹配,除了 const 部分。 And VC++ will gloss over that last small problem. VC++ 将掩盖最后一个小问题。 The easiest solution in MSVC is to use the _bstr_t wrapper type for BSTR , which does SysAllocString for you. MSVC 中最简单的解决方案是为BSTR使用_bstr_t包装器类型,它为您执行SysAllocString Else you'll need to do it manually.否则,您需要手动完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM