Click to See Complete Forum and Search --> : returning a string c++ to vb
agent
Nov 25th, 2002, 10:10 PM
I'm pretty sure this has been asked before, but I couldn't find it when I searched for it. How do I return a string the same way any other windows api function does it (such as GetSystemDirectory)?
I need to pass a buffer to the dll and have the dll fill the buffer. How can I do this in vc++?
(As you can probably tell, I'm just learning c++, but I have a strong knowledge of vb)
Sastraxi
Nov 25th, 2002, 11:25 PM
Well, have your function with it asking for a count and a char[]. Then, you can simply loop through and add your data from 0 to count - 2. Then, at count - 1, simply add the \0 at the end (string terminator). In any case, return the number of characters in the string. It would be called like this:Private Declare Function MyFunct Lib "MyLib.dll" (ByVal Count As Long, ByRef Str As String) As Long
Function GetFunct() As String
Dim Q As String
Dim Ret As Long
Q = Space(255)
Ret = MyFunct(255, Q)
GetFunct = Left(Q, Ret)
End Function
agent
Nov 25th, 2002, 11:32 PM
Actually, I meant the other side of the Declare. In c++, how would I create the function.
in MyLib.cpp...
int __stdcall Myfunct(int Count, ??? Str)
{
//...
return sizeof(Str);
}
what type should I use in place of the ??? in the above example
agent
Nov 26th, 2002, 01:57 AM
i modified a previous post that returned the string as the result of the function (i.e. 'return <string>;') to try to get this to work right. here is the source code of both the dll and the vb. this now causes "Bad Dll calling convention".
i have a .def file for the dll that exports 'test'
c++
#include <windows.h>
#include <stdio.h>
extern "C" __declspec(dllexport) int test(int nCount, BSTR lpTesting)
{
char *tmp = new char[nCount];
memset(tmp, ' ', nCount);
sprintf(tmp, "testing testing testing");
lpTesting = SysAllocStringByteLen(tmp, strlen(tmp));
return sizeof(lpTesting);
}
vb
Option Explicit
Declare Function test Lib "f:\vs\VC98\MyProjects\ID3\Debug\ID3.dll" (ByVal nCount As Long, ByVal lpReturn As String) As String
Sub t()
Dim a As String
a = Space(255)
a = Left(a, test(255, a))
Debug.Print a
End Sub
Sub main()
t
End Sub
Sastraxi
Nov 26th, 2002, 06:45 AM
Well- you're no longer using STDCALL. VB can only use STDCALL functions.
CornedBee
Nov 26th, 2002, 11:08 AM
This has indeed been asked very often.
You need a def file. You can't use sizeof(lpTesting) to determine the length of the string.
This function will simply allocate memory, the let the pointer stray. There are at least 3 threads that explain this well. Search this forum for "BSTR".
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.