I'm very new to interop and I am having trouble defining the dll imports from a C++ DLL. The documentation for the DLL is as follows:
bool __stdcall __declspec(dllexport) InitHW(char *name, char *model, int& type)
So the code I tried is as follows and it gives a system.AccessViolation exception:
[DllImport("extIO_IC7610.dll", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern bool InitHW(string name, string model, int type);
private unsafe void Initialize()
{
try
{
bool result;
string name = "Test";
string model = "Model";
int type = 3;
result = InitHW(name, model, type);
}
catch (Exception ex)
{
}
}
I just realized this is supposed to return data. Could someone please show me the errors in my understanding here? Thanks, Tom
Based on the comments I changed things to look like this:
[DllImport("extIO_IC7610.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public unsafe static extern bool InitHW(string name, string model, ref int type);
unsafe private void Initialize())
{
try
{
bool result;
string name = "";
string model = "";
int type = 3;
result = InitHW(name, model, ref type);
}
catch (Exception ex)
{
}
}
This still does not work. I now get an error that the stack is unbalanced due to the signatures not matching. I think the strings are done correctly but the &int parameter may still be an issue. Tom
ref int type... Not sure about the rest though I see no need forunsaferef intalready mentioned, note that the return type of your native C++ function is the C++ data typebool. Your DLLImport has to specifically account for that (the default marshalling for the C# data typeboolis the native WinAPI typeBOOL, which is different from the C++ data typebool). Why and how to do this exactly, see here: blogs.msdn.microsoft.com/jaredpar/2008/10/14/…; or see here: stackoverflow.com/questions/4608876/…