I have a solution which consists of two projects: a C# console app and a C library. The C library has a function which returns a HRESULT. I need to somehow change this function to get it to return a string to my C# code. This is how it should look:
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 } I can change both projects. However, there's no way of knowing how big the string will be. Therefore, I've tried allocating the string in the C lib but this lead to access violation exceptions and all sorts of problems. What would be the best way to tackle this?
StringBuilder, but without knowing the number of bytes to allocate in advance and since the function does not ask for the buffer's original length, this will lead to buffer overflows or access violations.refinstead ofout.outdoes not initialise the pointer*textto NULL, so if the native function is callingSysFreeStringto free the contents, it will cause an access violation. The proper answer though is to run it up in the debugger and find out where the access violation occurs, at which point all will probably be illuminated...