FormatMessage with parameters in C#

  • Thread starter Andy Robinson via .NET 247
  • Start date
A

Andy Robinson via .NET 247

i'm trying to call FormatMessage and supply some arguments for itto substitute into the message string. i can get it to grab themessage, but i can't convince it to substitute the arguments.

i've got the arguments in an ArrayList (though i started withthem in a byte array along the lines of a safe array (numparams,len p1, p1, len p2, p2, ...)). the arguments are always string,but the number of arguments varies from call to call. i'mpretty sure it's just a matter of getting it to marshalcorrectly, but so far i haven't guessed the magic format.

i currently have FormatMessage defined as:

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern int FormatMessage(
int dwFlags,
IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
out IntPtr MsgBuffer,
int nSize,
[MarshalAs(UnmanagedType.SafeArray,SafeArraySubType=VarEnum.VT_BSTR)] System.Collections.ArrayListArguments
);

//i munge the byte array into an ArrayList
System.Collections.ArrayList paramList =BuildParamList(parameters, parameterSize);

int dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM ;

dwFormatFlags |= (parameterSize == 0) ?FORMAT_MESSAGE_IGNORE_INSERTS : FORMAT_MESSAGE_ARGUMENT_ARRAY;

//i successfully load my message library as hModule usingLoadLibraryEx

IntPtr pMessageBuffer;
int msgid = //whatever message id i've been passed

dwBufferLength = FormatMessage(dwFormatFlags,
hModule,
msgid,
0,
out pMessageBuffer,
8096,
paramList);

when it hits the FormatMessage, i get an error that says: Cannot marshal parameter #7: The type definition of this type hasno layout information.

i've played around with a few different flavors of the MarshalAs- so far with no luck.

any hints would be appreciated. my backup plan just is tosubstitute the parameters myself. but it would be cool if icould get FormatMessage to do it for me.
 
M

Mattias Sjögren

Andy,
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern int FormatMessage(
int dwFlags,
IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
out IntPtr MsgBuffer,
int nSize,
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] System.Collections.ArrayList Arguments
);

Using an ArrayList won't work, try replacing it with a string array
(and remove the MarshalAs attribute).



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top