Help. Dllimport issues
Hi guys, I'm having real trouble marshalling Pinvoke data types. I am trying to access an API, and am attempting to convert the C header data into code pivoke
can use. I managed to get it to compile, but am a getting runtime error (see below). Any idea what I am doing wrong?
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Test.HubAPI.APIWrap.MsgConnect(Int32 lMsgAPIVersion, String lpcszTopic, OPERATOR lpOperator, IntPtr lphContext)
at Test.HubAPI.MainEntryPoint.Main() in c:\documents and settings\z76546\my documents\hubapi\class1.cs:line 190
This is the C header info:
#define APIFUNCTION int __stdcall
typedef void *MSGHANDLE;
typedef struct /* logon information structure */
{
char szOprId[OPERATORLEN + 1];
char szOprPswd[OPERATORLEN + 1];
} OPERATOR;
typedef OPERATOR *LPOPERATOR;
MSGAPIFUNCTION MsgConnect(long lMsgAPIVersion, const char *lpcszTopic, LPOPERATOR lpOperator, MSGHANDLE *lphContext);
This is my C# code:
public class APIWrap
{
...
public const int APIVERSION = 1;
public IntPtr hCtx;
...
[StructLayout(LayoutKind.Sequential,Pack=4)]
public struct OPERATOR
{
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=OPERATORLEN + 1)]
public string szOprId;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=OPERATORLEN + 1)]
public string szOprPswd;
};
[DllImport("C:\\dev\\bin\\msg.dll")]
public static extern int MsgConnect (int lMsgAPIVersion, string lpcszTopic, OPERATOR lpOperator, IntPtr lphContext);
}
class MainEntryPoint
{
static void Main()
{
int Result;
string IPAddress = "10.199.156.100:8020";
APIWrap currentEmployee = new APIWrap();
APIWrap.OPERATOR opr = new APIWrap.OPERATOR();
opr.szOprId = "logon";
opr.szOprPswd = "password";
Result = APIWrap.MsgConnect(APIWrap.MSG_APIVERSION, IPAddress, opr, currentEmployee.hCtx);
}
}
|