Re: Using PInvoke with string pointers

Tech-Archive recommends: Speed Up your PC by fixing your registry

From: DalePres (don-t-spa-m-me_at_lea-ve-me-a-lone--.com)
Date: 03/06/05


Date: Sun, 6 Mar 2005 16:42:37 -0600

This is one area where there are so many ways to get the job done that it
gets confusing. In short, you can use the MarshalAsAttribute or
Marshal.StringToHGlobalAnsi method or the related or its related
StringToHGlobalUni and StringToHGlobalAuto methods.

To get the string back from the pointer, there are corresponding
PtrToStringAnsi, PtrToStringUni, and PtrToStringAuto methods.

To pass a string buffer that will be changed by the PInvoke call and
returned as a parameter to the called function, pass a Text.StringBuilder.

Different methods of passing the pointer have different memory management
requirements for freeing up the memory after the string, and the pointer to
it, is no longer needed. Make sure you check the memory management sections
in any MSDN articles on these methods.

HTH

DalePres
MCAD, MCDBA, MCSE

"Bob Dankert" <bob@nospamnvsn-it.com> wrote in message
news:u275McpIFHA.3336@TK2MSFTNGP10.phx.gbl...
>I need to use functions through PInvoke which accept and return pointers to
>strings. What is the best way to get string pointers (IntPtr I am
>guessing?) to pass into these functions, and the best way to take the
>pointers (again, IntPtr I assume?) into strings?
>
> Thanks,
>
> Bob
>



Relevant Pages

  • Re: "Mastering C Pointers"....
    ... A pointer is a kind of variable that can "point to" some object. ... has a type (pointer to int), and a value of some kind. ... You may know that you can access these integers by using array notation ... The function will take one argument, a string, and will return the length ...
    (comp.lang.c)
  • Re: pesky Pointers !!
    ... > and the function takes it as a reference instead of a copy. ... function may access the string passed directly, ... > *px dereferences the pointer to get the value ... If pTest is a pointer-to-string, *pTest is the string it points to ...
    (alt.comp.lang.learn.c-cpp)
  • Re: strtok ( ) help
    ... > splitCommandssomehow modifying the pointer, but I HAVE to call that ... Here's an idea of how to use the strtok() function. ... don't mind trashing the contents of a string s, ... will give you a loop that extracts the tokens one at a time from s. ...
    (comp.lang.c)
  • Re: new IL: C (sort of...).
    ... C doesn't need a string type... ... variant of PL/1 which was very Pascal-ish. ... - C does implement an array declaration. ... effectively converted into a pointer that can be used with the offset ...
    (comp.lang.misc)
  • Re: copy a string into a 2d array of chars
    ... This split function should allocate a 2D array of chars ... >focus the program the string is not actually split. ... later) is an array of char containing the original contents of the ... The i-th pointer will contain the starting address of the ...
    (comp.lang.c)