How can I return a PChar from a DLL function to a VB6 application without risking crashes or memory leaks?

前端 未结 7 1498
花落未央
花落未央 2020-12-19 05:37

I have to create a DLL which is used by a VB6 application. This DLL has to provide several functions, some of them must return strings.

This is the VB6 declaration:<

相关标签:
7条回答
  • 2020-12-19 06:19

    I'm not familiar with Dephi, but here are the two main options when using strings with a non-COM DLL and VB6.

    Option 1. Use "ANSI" strings.

    'DLL routine expecting to be passed pointers to ANSI strings '
    'VB6 will allocate and deallocate the strings '
    'Its vital that VB6 allocates sufficient space for the return string '
    Declare Sub MyProc Lib "mylib.dll" (ByVal Param As String, _ 
      ByVal OutVal As String) 
    
    Function DoMyProc(ByVal Param As String) As String
      Dim sResult As String
      sResult = Space$(255)  ' create 255 bytes of space for the return string '
      Call MyProc(Param, sResult) 
      DoMyProc = sResult
    End Function
    

    Option two. Use BSTRs.

    'DLL routine expecting to be passed two BSTRs. It will modify the second one. '
    'VB6 "owns" both BSTRs and will deallocate them when it has finished with them. '
    Declare Sub MyProc(ByVal lpParam As Long, ByVal lpOutVal As Long)
    
    Function DoMyProc(ByVal Param As String) As String
      Dim sResult As String
      Call MyProc(StrPtr(Param), StrPtr(sResult)) 
      DoMyProc = sResult
    End Function
    

    I'd also suggest looking at the Microsoft advice on writing C DLLs to be called from VB. Originally released with VB5 but still relevant to VB6.

    0 讨论(0)
提交回复
热议问题