Marshalling a char** in C#

前端 未结 2 445
别跟我提以往
别跟我提以往 2021-02-08 12:34

I am interfacing with code that takes a char** (that is, a pointer to a string):

int DoSomething(Whatever* handle, char** error);

2条回答
  •  孤城傲影
    2021-02-08 12:52

    For reference, here is code that compiles (but, not tested yet, working on that next tested, works 100%) that does what I need. If anyone can do better, that's what I'm after :D

    public static unsafe int DoSomething(IntPtr handle, out string error) {
        byte* buff;
    
        int ret = DoSomething(handle, &buff);
    
        if(buff != null) {
            int i = 0;
    
            //count the number of bytes in the error message
            while (buff[++i] != 0) ;
    
            //allocate a managed array to store the data
            byte[] tmp = new byte[i];
    
            //(Marshal only works with IntPtrs)
            IntPtr errPtr = new IntPtr(buff);
    
            //copy the unmanaged array over
            Marshal.Copy(buff, tmp, 0, i);
    
            //get the string from the managed array
            error = UTF8Encoding.UTF8.GetString(buff);
    
            //free the unmanaged array
            //omitted, since it's not important
    
            //take a shot of whiskey
        } else {
            error = "";
        }
    
        return ret;
    }
    

    Edit: fixed the logic in the while loop, it had an off by one error.

提交回复
热议问题