Search code examples
.netpointersintptr

Getting a buffer from a pointer


This is the code I got the get the last error into a buffer, but I have no idea how to get the IntPtr converted to something I could read... I just get a long number.

/// Return Type: void
///pErrorCode: ABS_DWORD*
///ppErrorMessage: ABS_CHAR**
        [System.Runtime.InteropServices.DllImportAttribute("bsapi.dll", EntryPoint = "ABSGetLastErrorInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        public static extern void ABSGetLastErrorInfo(ref uint pErrorCode, ref System.IntPtr ppErrorMessage);

This is from the manual:

void ABSGetLastErrorInfo(
OUT ABS_DWORD *pErrorCode
OUT const ABS_CHAR **ppErrorMessage
)

Description Retrieves additional information about last BSAPI error, which occurred in the current thread.

ppErrorMessage On output this is set to point to a buffer containing zero-terminated string with textual message.

If no message is provided, it points to empty string so the caller does not need check it for NULL.

The buffer is managed by BSAPI; do not use ABSFree to release it. Note that the buffer is valid only until other BSAPI call is performed in the same thread. After the next call, the buffer may be released or reused by BSAPI. If you need to remember the message, you have to copy it into your own buffer.


Solution

  • Define as

     public static extern void ABSGetLastErrorInfo(ref uint pErrorCode, StringBuilder ppErrorMessage);
    

    StringBuilder is used for Output strings. See here.

    If the string parameter can be input and/or output, then use the System.StringBuilder type. The StringBuilder type is a useful class library type that helps you build strings efficiently, and it happens to be great for passing buffers to native functions that the functions fill with string data on your behalf. Once the function call has returned, you need only call ToString on the StringBuilder object to get a String object.


    UPDATE

    As Jim Kindly mentioned, define the StringBuilder as ref.

    public static extern void ABSGetLastErrorInfo(ref uint pErrorCode, ref StringBuilder ppErrorMessage);