本帖最后由 lincolnxu0116 于 2011-12-14 16:27:27 编辑

解决方案 »

  1.   

    http://stackoverflow.com/questions/6089214/how-do-i-marshal-wchar-t-from-c-to-c-sharp-as-an-out-parameter-or-return-valu
      

  2.   

    http://topic.csdn.net/u/20110804/09/f35a170c-fee4-42be-83f4-abcc54ad6987.html
      

  3.   


    There's another big problem.  The callee of this function must release the string.  The C# code cannot do this, it doesn't have access to the unmanaged C/C++ heap allocator.  You'll leak memory for every call.The C/C++ code must look like this:extern "C" __declspec int myfunct(wchar_t* buffer, size_t bufsize)
    {   
        wcscpy_s(buffer, bufsize, L"Hello world");
        return 1;
    }And your C# code like this:  [DllExport("something.dll", CharSet = CharSet.Unicode)]
      private static extern int myfunct(StringBuilder buffer, int bufsize);
    ...
        sb = new StringBuilder(666);
        int retval = myfunct(sb, sb.Capacity);
        string s = sb.ToString();我按照此方法更改之后仍然抛出一样的问题。
    请问如何改善。
      

  4.   

    那你用 string 试下StringBuilder也有可能是长度不对
      

  5.   

    非常感谢我已经解决了。c#代码:
    StringBuilder LogPath = new StringBuilder(xxxx);
    InitLogWorkDir(LogPath.ToString());接口:
    [DllImport("xxxx.dll",xxxxxxx,CallingConvention = CallingConvention.StdCall)]
    private static void InitLogWorkDir([MarshalAs(UnmanagedType.LPWStr)]string logDir);C++代码:
    void InitLogWorkDir(LPWSTR logDir)
    {
    wstring logDirWStr = logDir;
    Log::SetPath(logDirWStr);
    return;
    }  
      

  6.   

    c#代码:
    StringBuilder LogPath = new StringBuilder(xxxx).Append("ssssss");
    InitLogWorkDir(LogPath.ToString());