title: Call a function in a C DLL from VB: Access Violation
body: <p>I'm trying to call a Dll function which looks like this (in the C/C++ Dll):</p>
  
  <pre><code>__declspec(dllexport) void execute(char** ReturnMsg, char* serverAddress, char* commandLine)
  </code></pre>
  
  <p>The VB 'wrapper' function looks like:</p>
  
  <pre><code>&lt;DllImport("TPClient.dll", EntryPoint:="execute", CallingConvention:=CallingConvention.Cdecl, CharSet:=CharSet.Auto, ExactSpelling:=True)&gt; _
  Public Shared Sub tg_execute(&lt;Out()&gt; &lt;MarshalAs(UnmanagedType.LPStr)&gt; ByRef returnString As System.Text.StringBuilder, _
                               &lt;MarshalAs(UnmanagedType.LPStr)&gt; ByVal serverAddress As String, _
                               &lt;MarshalAs(UnmanagedType.LPStr)&gt; ByVal commandLine As String)
  End Sub
  </code></pre>
  
  <p>The parameters are:
  returnString: a string I need to get back from the function, result of the command sent;
  serverAddress: a string, input only (an IP or DNS name); and 
  commandLine: a string, input only (any command)</p>
  
  <p>To call the function, I make a StringBuilder object with some sufficient capacity to use as the returnString variable:</p>
  
  <pre><code>Dim returnString As New System.Text.StringBuilder(128)
  
  tg_execute(returnString, TextBox_serverName.Text.Trim, TextBox_Command.Text.Trim)
  </code></pre>
  
  <p>When I run the code, I do get the expected string in the returnString (as I can see in the debugger), however I also get an AccessViolationException. So, I get for example "2.6.30.8-x86" in returnString when I use the command "uname -r" in commandLine. But the code hangs due to the memory error. </p>
  
  <p>Now I'm not too familiar with VB and P/Invoke, and I had to do some trial and error to get the arguments passed to the DLL (which I'm also writing and debugging). This is also how I ended up using the "MarshalAs(UnmanagedType.LPStr)" attributes. However now I don't know why I'm getting these memory errors.</p>
  
  <p>I made some other attempts using IntPtr arguments, but I also couldn't get this working and gave up on that approach, as to my understanding the marshaling should be handled automatically (is that correct?).</p>
  
  <p>Any help is much appreciated.</p>