我们的一位技术人员要求我编写一个小库文件,他将在其中传递一个文件名和一个整数。该库将加载文本文件并在文件名引用的文本文件中查找整数,并将一个字符串返回给他的程序。他正在开发一个使用 VB 作为脚本语言的第三方应用程序。
因此,不想担心他安装了设备的一些旧机器上的 .net 安装问题,我决定尝试一下 C++(VS 2010)。我正在使用 C# 进行应用程序开发,上次编译任何 C++ 代码是在 VS 6 中,但我想这有多难?好吧,我在这里打字,所以事情已经发生了明显的错误。我从 C++ 端开始。
#include <WTypes.h>
#include <comutil.h>
#include <string.h>
BSTR _stdcall regExConv(BSTR fileName, int modNumber);
BSTR _stdcall regExConv(BSTR fileName, int modNumber) {
string inText;
// open the file and read in the text from the file
ifstream testFile;
testFile.open("C:\\Test\\testFile.txt", ifstream::in);
if(testFile.fail())
MessageBox(NULL,L"Failed to Open", NULL, NULL);
while (testFile.good())
getline(testFile, inText);
testFile.close();
_bstr_t passString(inText.c_str());
BSTR finalPass = passString.copy();
return finalPass;
}
效果很好。 FinalPass 为我提供了文本文件中的测试字符串。
Locals Window:
inText "eeeeeeeee" std::basic_string<char,std::char_traits<char>,std::allocator<char> >
passString {"eeeeeeeee" (1)} _bstr_t
finalPass 0x00722214 "eeeeeeeee" wchar_t *
在 VB 方面我有这个。
Public Class Form1
Private Declare Function testFunc Lib "c:\Development\gTP3200\Debug\gTP3200.dll" (ByVal testVar As Integer) As Integer
Private Declare Function stringTest Lib "c:\Development\gTP3200\Debug\gTP3200.dll" (ByVal Str As String) As String
Private Declare Function regExConv Lib "c:\Development\gTP3200\Debug\gTP3200.dll" (ByVal fileString As String, ByVal faultedMod As Integer) As String
Private Declare Function stringBack Lib "c:\Development\gTP3200\Debug\gTP3200.dll" () As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim retVal As String
retVal = regExConv("file name pass", 3)
End Sub
End Class
两人聊得很好,问题是返回到 VB 端的字符串只是 inText
中的第一个字符。
Locals Window:
retVal "e" String
两天来,我试图阅读所有有关它的内容,但我开始感觉自己像是在演一部糟糕的 Monty Python 短剧。似乎没什么用。我尝试将字符串转换为各种其他类型,然后再转换回 BSTR。尝试了 SysAlloc,但没有成功。
如果我将一个字符串作为参数传递给 BSTR,然后再次将其传递回来(如文件名),那么 VB 端会读取整个字符串。
最佳答案
您尝试过 MarshalAs 吗?
Private Declare Function stringBack Lib "c:\Development\gTP3200\Debug\gTP3200.dll" () As <MarshalAs(UnmanagedType.BStr)> String
关于C++ DLL 仅向 VB 应用程序返回第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10416152/