我有一个由两个项目组成的解决方案:一个C#控制台应用程序和一个C库。C库有一个返回HRESULT的函数。我需要以某种方式更改此函数,使其向C#代码返回一个字符串。它应该是这样的:
C#:
[DllImport("MyLib.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern long MyFunction(bunch of params, [MarshalAs(UnmanagedType.BStr)] out string text);
C:
extern "C" HRESULT __declspec(dllexport) MyFunction(bunch of params, BSTR* text)
{
PWSTR finalResult;
//lots of code
(*text) = SysAllocString(finalResult);
//cleanup code
}
我可以改变这两个项目。然而,没有办法知道字符串会有多大。因此,我尝试在C库中分配字符串,但这会导致访问冲突异常和各种问题。解决这个问题的最好方法是什么?
https://stackoverflow.com/questions/8126662
复制相似问题