VB Marshal problem

  • Thread starter Thread starter Vincent Schmid
  • Start date Start date
V

Vincent Schmid

Hello,

I've declared a VB callback Sub which is called by an unmanaged DLL (code
below). The PData parameter is a pointer to a memory bloc which is allocated
and freed by the dll as necessary.

The RequestFunc should read a string pointed by PData, and replace it by
another one. The problem arises when the Sub tries to write the answer :
there is an error when calling Marshal.PtrToStringAnsi. (The RequestFunc is
not supposed to free the memory bloc pointed by PData)

What's wrong with the following code ? (note : the buffer is allocated for
sure, and is large enough)

Many thanks for comments,
Sincerely
Vincent


Sub RequestFunc(ByVal PData As IntPtr, ByVal DataSize As Int32)

Dim Request As String
Dim Answer As String

Request = Marshal.PtrToStringAnsi(PData, DataSize)
MsgBox(Request)
Answer = "This is the answer"
Marshal.StructureToPtr(Answer, PData, False)
End Sub
 
Vincent,
What's wrong with the following code ? (note : the buffer is allocated for
sure, and is large enough)

The problem is that a string isn't a structure. Try this instead

Dim chars() As Char = (Answer & ChrW(0)).ToCharArray()
Marshal.Copy(chars, 0, PData, Math.Min(chars.Length, DataSize))



Mattias
 
Mattias,

Thanks a lot for your help, it almost works now. However there is still a
small problem : The dll was expecting an Ansi string, not a unicode one.

If there is a simple way to convert the data which goes into the buffer to a
Ansi string, I would be happy to know it. In any case, it's not a problem to
modify the dll so that it recognizes the unicode string.

Have a nice day,
Vincent
 
Vincent,
Thanks a lot for your help, it almost works now. However there is still a
small problem : The dll was expecting an Ansi string, not a unicode one.

Ok, then you can do

Dim chars() As Byte = System.Text.Encoding.Default.GetBytes(Answer &
ChrW(0))
Marshal.Copy(chars, 0, PData, Math.Min(chars.Length, DataSize))



Mattias
 
Back
Top