Using PInvoke with string pointers

  • Thread starter Thread starter Bob Dankert
  • Start date Start date
B

Bob Dankert

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
 
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
 
Thanks a lot - this worked perfectly!

Bob

DalePres said:
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
 
Back
Top