Link to home
Start Free TrialLog in
Avatar of shaii
shaii

asked on

DLL return String into Visual Basic 6.0

Hi,
 I have I DLL written in C++.
In it is a function that returns a string. I want to call this function from VB6 but I am having some problems.

I have an api for VB .NET:
<DllImport("myDll.dll", CharSet:=CharSet.Unicode)> _
    Public Shared Function GetText() As String
    End Function

Note: the Unicode

and from the c++ .h file:
extern "C" LPTSTR __stdcall GetText();

I tried to declare it in Visual Basic 6.0
Public Declare Function GetText Lib "myDll.dll" () As Long

but can't manage to get the text from the Long (I am assuming this is a pointer to the string).
I may be wrong and the declare is off.

Thanks...
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

You would need to pass the string as a fixed sized char array.

The C++ function than may have the prototype

   int getText(char* buf, int siz);

and should return the number of bytes (<= siz) copied to the buf.

In VB you would declare the buf as string and make a proper allocation, e. g. by adding spaces.

Regards, Alex
Avatar of shaii
shaii

ASKER

I do NOT have the dll code so I can't manipulate the method in the DLL.

I am sure (well I really hope) that this can be done without changing the dll.

Thanks for your help
Avatar of jkr
Try

<DllImport("myDll.dll", CharSet:=CharSet.Auto)> _
    Public Shared Function GetText() As String
    End Function

if you aren't sure if the DLL is compiled as UNICODE.
>>>> I am sure (well I really hope) that this can be done without changing the dll.

Actually, it is very bad (dll) design returning a newly allocated string which rarely can be freed by the calling VB function. It isn't much better if the string returned is a static buffer that doesn't need to be freed cause it makes the function not being reentrant, i. e. you can't call it twice without saving the first string somehow. If you look for samples of GetText functions provided by WINAPI you will see that they never return a char buffer but always are filling a passed buffer.

should it be

Public Declare Function GetText Lib "myDll.dll" () As string
instead of
Public Declare Function GetText Lib "myDll.dll" () As Long
Avatar of shaii

ASKER

Hi,
 I'll try from the first:
try <DllImport("myDll.dll", CharSet:=CharSet.Auto)> _
    Public Shared Function GetText() As String
    End Function
I am using VB6 and not .NET (for .NET it's working)
try
Public Declare Function GetText Lib "myDll.dll" () As string
instead of...
this causes vb to either Crash or in RunTime there is an error.

HELP!!!
ASKER CERTIFIED SOLUTION
Avatar of shaii
shaii

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial