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();我按照此方法更改之后仍然抛出一样的问题。 请问如何改善。
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();我按照此方法更改之后仍然抛出一样的问题。
请问如何改善。
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;
}
StringBuilder LogPath = new StringBuilder(xxxx).Append("ssssss");
InitLogWorkDir(LogPath.ToString());