开发者

VB.NET pointer interop question

I am trying开发者_如何学Python 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?


<StructLayout(LayoutKind.Sequential)> _
public structure foo
  <MarshalAs(UnmanagedType.LPStr)> dim msg as string
  dim msgLen as integer
end structure


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜