[Mono-dev] Specifying MarshallAs for [Out] StringBuilder

D Bera dbera.web at gmail.com
Sun Mar 23 17:28:23 EDT 2008


Hi,

>  In this case you only need to allocate a buffer large enough to hold the
>  string using AllocHeap, call PtrToString on the result, and FreeHeap on the
>  buffer.

I understood that I have to use a StringBuilder with a large enough
buffer. But what I don't understand is how do I get access to the
underlying pointer from the StringBuilder ? Are you suggesting that I
don't rely on Mono's marshalling of stringbuilder<->read-write_string
but instead write my own marshaller; something like this ?

To call my_func which is like:
private static extern void my_func ([out] StringBuilder sb, int capacity);

I instead use manual marshalling and do
[Dllimport(..)]
private static extern void my_func(IntPtr buffer);

public static extern void call_my_func (StringBuilder sb, int capacity)
{
  // 1. Creata a large buffer using AllocHeap
  IntPtr buffer = AllocHeap (capacity or more to contain encoded value);
  // 2. Call native function
  my_func (buffer);
  // 3. Read back string and fill in the stringbuilder
  sb.Length = 0;
  sb.Append (do some encoding stuff with PtrToString on the buffer);
  // 4. Free buffer
  FreeHeap (buffer);
}

Thanks a lot. I am already beginning to understand marshalling and
p/invoke better :)
- dBera

-- 
-----------------------------------------------------
Debajyoti Bera @ http://dtecht.blogspot.com
beagle / KDE fan
Mandriva / Inspiron-1100 user


More information about the Mono-devel-list mailing list