tags:

views:

36

answers:

2

I am trying to write a VB.NET program that will call a function in an unmanaged C DLL passing the structure like this:

typedef struct {
    unsigned char *msg; 
    int msglen;         
}

What I have not been able to figure out is how to handle the "unsigned char *msg" part. How would you define this in the VB.NET Structure?

+1  A: 

This depends a lot on how the memory for the msg field is handled. You need to be careful to free any allocated memory which is transfered to managed code.

That being said I think the most straight forward interop type is as follows

Public Structure S1 
  Public msg as IntPtr
  Public msgLen as Integer
End Structure

To get the actual msg value as a String you'll need to use the following code.

Public Function GetString(ByVal s1 as S1) As String
  return Marshal.PtrToStringAnsi(s1.msg, s1.msgLen)
End Function

To create an S1 instance based on a String do the following. Note: You will need to free the memory allocated here if the calling function does not take ownership.

Public Function CreateS1(ByVal str As String) As S1
  Dim local As New S1
  local.msg = Marshal.StringToHGlobalAnsi(str)
  local.msgLen = str.Length
  return local
End Function
JaredPar
I need the VB.NET code to pass msg to the function, how do I set the msg pointer in the strucutre?
Dan B
@Dan, updated the answer to include that.
JaredPar
The same critique applies here. The odds that the unmanaged code will use the process heap are minuscule. The only hope the OP has is that the code doesn't try to release the string. In which case your version will leak.
Hans Passant
@Hans I agree it's dicey at best. I prefer this solution because it makes the memory management issue more explicit and ideally draws greater criticism. It's impossible to give a prefect answer without knowing more about the native code the OP is calling.
JaredPar
+1  A: 
<StructLayout(LayoutKind.Sequential)> _
public structure foo
  <MarshalAs(UnmanagedType.LPStr)> dim msg as string
  dim msgLen as integer
end structure
GSerg
This makes heavy assumptions about how the memory for msg is allocated and whether or not it's null terminated.
JaredPar
Correct. However, expected level of confidence is more than 90% (i.e., I'm quite sure this is no different to all other examples of passing unmanaged strings around).
GSerg