Re: am having a problem with pinvoke and StringBuilder[ ]
- From: Pavel Minaev <int19h@xxxxxxxxx>
- Date: Wed, 30 Apr 2008 12:43:48 -0700 (PDT)
On Apr 29, 7:52 pm, "LK" <lkant2...@xxxxxxxxx> wrote:
From a C# program I need to access an existing DLL that enumerates the
boards detected via a hardware probe of the system. The function that
does the enumeration expects an int * where it stores the number of boards
detected and a char *** where it stores the name of each board detected.
Since the String class is immutable, I have used StringBuilder in my code
but this results in a NullPointerException. Just for testing, I replaced
StriingBuilder[] with String[] and the code worked just fine (i.e, no
NullPointerExceptions occured and all messages populated in
the String[] in managed code was correctly printed by the DLL).
Note that String is only immutable from within .NET (and even then
only if you don't access it via pointers), and immutability is not
enforced in unmanaged code. If you pass a String to a function that'll
write something into it, it'll work just fine - just be sure to create
a new instance of string (e.g. via "new string('\0', capacity)")
specifically for this purpose, so that you hold the only managed
reference to it.
I am wondering what I am doing wrong in my code. For reference, I am
enclosing my C# code and my sample DLL code
You are doing it logically, but unfortunately, P/Invoke only supports
StringBuilders as top-level function arguments - arrays of
StringBuilder, or fields of type StringBuilder inside marshalled
structs, are not supported (you get a meaningful exception for the
latter telling you as much, at least, but the former just passes some
weird data to the function called).
Therefore, you have three options: either use plain strings as
described above, use IntPtr and marshal stuff manually using the
Marshal.PtrToStringAnsi and Marshal.StringToHGlobalAnsi as needed, or
use plain unsafe pointers (byte*** in your case) and handle
conversions & allocations manually as you see fit (e.g. stackalloc /
Encoding.GetBytes / Encoding.GetChars).
.
- References:
- Prev by Date: Re: am having a problem with pinvoke and StringBuilder[ ]
- Next by Date: Re: View windows forms control in a web page
- Previous by thread: Re: am having a problem with pinvoke and StringBuilder[ ]
- Index(es):
Relevant Pages
|