1

I need to pass data from a VB6 app to a managed VB.NET assembly DLL. For this purpose, I'm successfully using DLLExport from RGiesecke, and using appropriate marshalling, I can pass any type I want (strings, numbers, etc...).

Now, instead of passing single parameters, for convenience I want to use a struct. This is my code:

VB.NET side

Imports RGiesecke.DllExport
Imports System.Runtime.InteropServices
Public Module myLib
    <System.Runtime.InteropServices.StructLayoutAttribute(
        System.Runtime.InteropServices.LayoutKind.Sequential,
        Pack:=4,
        CharSet:=System.Runtime.InteropServices.CharSet.Ansi)>
    Structure sStruct
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128)> Dim nome As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128)> Dim cognome As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=32)> Dim codfis As String
        <MarshalAs(UnmanagedType.I2)> Dim eta As Short
    End Structure

    <DllExport()>
    Public Sub getStruct(<MarshalAs(UnmanagedType.Struct)> ByRef p As sStruct)
        p.nome = "NOME"
        p.cognome = "COGNOME"
        p.codfis = "CODFIS"
        p.eta = 33
    End Sub
End Module

VB6 side

Private Type sStruct
    nome As String * 128
    cognome As String * 128
    codfis As String * 32
    eta As Integer
End Type

Private Declare Sub getPatient Lib "myLib.dll" (ByRef p As sStruct)
Private Sub Command1_Click()
    Dim pp As sStruct
    getPatient pp
    MsgBox """" & pp.nome & """"
End Sub

I correctly get the values, however the strings are not terminated correctly, because I don't get the final quote in the msgbox. I think that strings are getting null-terminated, and VB6 doesn't like that.

Thanks for any help

JohnKiller
  • 2,008
  • 18
  • 28
  • 2
    Gieseke's tool is exceedingly difficult to use effectively. Slight mistakes turn into very hard to debug problems. Like getting the MarshalAs attribute wrong. There's no point to it when there are better alternatives. There are, VB.NET already is *very* capable of interoperating with VB6. Use the `` attribute. – Hans Passant Sep 08 '14 at 17:34
  • On the VB6 side you have to find the null and resize the string – David Heffernan Sep 08 '14 at 18:11
  • 1
    For instance TrimToNull from here: http://www.cpearson.com/excel/sizestring.htm – David Heffernan Sep 08 '14 at 18:53
  • Related: [Fixed length strings or structures in C#](http://stackoverflow.com/q/415214/588306) and [Marshal NOT 0 terminated string](http://stackoverflow.com/q/11556852/588306). – Deanna Sep 10 '14 at 09:17

0 Answers0