Vb6 code to run on the following error.
How can I fix the error?
How can I return a normal string?
vb6 code
Private Declare Function DllPchar Lib "C:\TEST\Project2.dll" (ByVal AStr As String) As String
Private Sub Command10_Click()
Dim tmp as String
tmp = DllPchar("123");
End Sub
Delphi7 code
function DllPchar( AStr: PChar) : PChar; stdcall;
Well, you haven't given much information about this problem. For instance, the error message. And the Delphi code for "DllPChar".
But never mind. The first thing I notice is that your Declare Function statement is returning a String. This will not work because VB is expecting a value of type BSTR to be returned. Delphi has a
WideString
type which is compatible withBSTR
.The reason why this is important is because VB strings are internally UTF-16, i.e. 2 byte per character Unicode Strings that are allocated by the COM memory manager. The Delphi PAnsiChar type is a pointer to an 8-bit ANSI character, and Delphi strings are allocated by Delphi's own memory manager. They are incompatible. However, there is a special case in VB6 where you can use
Declare Function
with a parameterByVal ... As String
, and VB handles and automatic conversion between a VB string and PAnsiChar before the call, and then between PAnsiChar and VB string after the call.If you can't use BSTR in Delphi, your best bet is to rewrite DllPchar() so that it modifies the
AStr
parameter. Or alternatively, create a new parameter to return the value in.If you can use BSTR, then you can modify
AStr
to pass itByRef
rather thanByVal
. This will allow you to pass in a Unicode string from VB. You then return your result via the return value.