I’m having some trouble marshalling a structure in a call to an external library function. I get no errors from the call itself but the function returns an error code that indicates it hasn’t properly understood the values being passed in.
Here’s the signature of the C function
DLLExport int connect(Client handle, connectOptions* options);
And here is my internal function
[DllImport("some.dll", CharSet = CharSet.Auto, ExactSpelling = false,
CallingConvention = CallingConvention.Cdecl)]
private static extern int connect(IntPtr client, connectOptions options);
Here is the specification for the connectOptions struct that I am working with
char struct_id [4]
int struct_version
int keepAliveInterval
int cleansession
int reliable
willOptions * will
char * username
char * password
int connectTimeout
int retryInterval
And then finally is my class within my application
[StructLayout(LayoutKind.Sequential)]
public class connectOptions
{
public byte[] struct_id;
public Int32 struct_version;
public Int32 keepAliveInterval;
public Int32 cleansession;
public Int32 reliable;
public willOptions will;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 128)]
public string username;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 128)]
public string password;
public Int32 connectTimeout;
public Int32 retryInterval;
public connectOptions()
{
struct_id = Encoding.ASCII.GetBytes("WXYZ");
struct_version = 0;
keepAliveInterval = 20;
cleansession = 1;
reliable = 0;
username = string.Empty;
password = string.Empty;
connectTimeout = 10;
retryInterval = 1;
will = null;
}
}
[StructLayout(LayoutKind.Sequential)]
public class willOptions
{
public byte[] struct_id;
Int32 struct_version;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 128)]
public string topicName;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 128)]
public string message;
public Int32 retained;
public Int32 qos;
public willOptions()
{
struct_id = Encoding.ASCII.GetBytes("VWXY");
struct_version = 0;
}
}
I think you have to decorate
struct_idlike this:otherwise the C# struct will contain a reference to an array, whereas the C++ one contains the actual 4 byte array.