I have the following function:
bool __declspec(dllexport) COMS_HL7QueryAnswer(char *szZone,char* szMessage, char** o_szAnswer)
And I’m PInvoking it from C# like this:
public static extern bool COMS_HL7QueryAnswer(string szZone,string szMessage, out StringBuilder szAnswer);
It’s working in Windows 2003 but I’m getting access violation exceptions in W2008 and looks like they happen in the boundary of the PInvoke. Any help will be great.
Thanks.
EDIT: Looks like the AccessViolationException happens in the PInvoke boundary because:
- I don’t have a callstack other than the C# function.
- When I go with the debugger I can F10 until the last C++ function and when I exit the } then I go to the C# exception handler.
You’ll need to use
Because p/invoke has no idea how to correctly free
*o_szAnswer, you’ need to keep the pointer and pass it to the correct deallocation function yourself, after retrieving the data.If you are allowed to change the C++ side, there are a number of things you can do to make this more p/invoke-friendly. Or you can use a C++/CLI layer.