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
Well I solved it. There were a couple of hints here but nothing really correct. After looking around for the last several hours this is the solution:
[DllImport("extIO_IC7610.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public unsafe static extern bool InitHW(StringBuilder name, StringBuilder model, int* type);
unsafe void Initialize()
{
bool result;
int type = 0;
var name = new StringBuilder(250);
var model = new StringBuilder(250);
result = InitHW(name, model, &type);
string _name = name.ToString();
string _model = model.ToString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.