1

I have a third party lib that has the following signature:

int GetError(char *Message, int Length)

Here the Message has to be a buffer of at least size Length, otherwise the function fails. How would one PInvoke this? I have tried Stringbuilder for the message, but here I cannot specify the length and the function fails.

The Message parameter is declared as an input parameter to the function.

Frank
  • 2,446
  • 7
  • 33
  • 67

1 Answers1

4

This is a routine scenario. You are asking the callee to populate a buffer allocated by the caller. That's the domain of StringBuilder.

The p/invoke declaration would be:

[DllImport(dllname, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.???)]
public static extern int GetError(StringBuilder message, int length);

You presumably know what the calling convention is, and can fill it in.

You then call the function like this:

StringBuilder message = new StringBuilder(256);
int retval = GetError(message, message.Capacity);
// check retval for error conditions
string error = message.ToString();
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Hehe this is why I linked to your answer in the comments above :) – DavidG Jul 12 '17 at 14:50
  • Thanks, but unfortunately I am getting an error: 'System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.' – Frank Jul 12 '17 at 15:06
  • Likely the problem is that the details are not as you have described in the question. If you create a simple C++ test DLL with a function of the same prototype as that in the question you will find that the code outlined here works fine. Obviously I cannot debug code that I cannot see. Quite often people asking get the details wrong. Check again. – David Heffernan Jul 12 '17 at 15:07
  • I understand. Perhaps the fact that the Message parameter is defined as an input parameter is relevant? I was assuming that it was a mistake in the documentation. – Frank Jul 12 '17 at 15:12
  • Hard to imagine that it is anything other than an output parameter. It's not const, you specify a length. Surely a string is returned to the caller. No? – David Heffernan Jul 12 '17 at 15:13
  • That is what I thought. It is indeed used to be able to read an error message. – Frank Jul 12 '17 at 15:19