Home > Back-end >  Assign a string to a byte array in a VBA user-defined type
Assign a string to a byte array in a VBA user-defined type

Time:12-02

I work with a relay module that I normaly connect via USB. That all works perfectly. Now I would like to connect it via the network. All manufacturer's VB.NET code works in vba except for accessing this module over the network.

Public Declare PtrSafe Function DapiOpenModuleEx Lib "DELIB64" (ByVal moduleID As Long, ByVal nr As Long, ByRef exbuffer As DAPI_OPENMODULEEX_STRUCT, ByVal open_options As Long) As Long


' Definitions for DapiOpenEx

Public Type DAPI_OPENMODULEEX_STRUCT
    address(255) As Byte
    timeout As Long
    portno As Long
    encryption_type As Long
    encryption_password(31) As Byte
End Type


'Open ETH-Module with parameter
    Dim handle as Ulong
    Dim MyModuleID As UInt32
    MyModuleID = 42

    Dim open_buffer As New DELib64.DAPI_OPENMODULEEX_STRUCT

    open_buffer.address = System.String.Copy(192.168.1.1 As String) As String 
    open_buffer.portno = 0

    handle = DELib.DapiOpenModuleEx(MyModuleID, 0, open_buffer)

I am getting an error "open_buffer.address = System.String.Copy(192.168.1.1 As String) As String "

Can someone help me with what i need to change here?

    Dim handle as LongLong 
    Dim MyModuleID As Long
    MyModuleID = 42


    Dim open_buffer As Delib64.DAPI_OPENMODULEEX_STRUCT
    open_buffer.address = system.String.Copy("192.168.1.1" AS String) As String
    open_buffer.portno = 0
    
    handle1 = DapiOpenModuleEx(MyModuleID, 0, open_buffer, 0)

CodePudding user response:

According to your comment, the original line of code is

strcpy((char*) open_buffer.address, "192.168.1.10");

So you need to copy the ASCII (single-byte) string "192.168.1.10" into a VBA byte array. This is surprisingly hard, since the obvious approach of open_buffer.address = StrConv("192.168.1.10", vbFromUnicode) won't work (you can't assign to a fixed-size array that's part of a type).

One obvious solution would be to make a Windows API call to CopyMemory, but if we want a VBA-only solution, a simple loop should suffice:

Dim i As Long
Dim b() As Byte
b = StrConv("192.168.1.10", vbFromUnicode)

For i = 0 To UBound(b)
    open_buffer.address(i) = b(i)
Next
open_buffer.address(UBound(b)   1) = 0     ' C-strings need to be 0-terminated

(I do have the feeling that this should be easier, so I'll gladly upvote competing, simpler answers.)

  • Related