[英]Access C++ DLL from C# program
我对互操作很陌生,我在定义从 C++ DLL 导入的 dll 时遇到了问题。 DLL 的文档如下:
bool __stdcall __declspec(dllexport) InitHW(char *name, char *model, int& type)
所以我尝试的代码如下,它给出了 system.AccessViolation 异常:
[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)
{
}
}
我刚刚意识到这应该返回数据。 有人可以在这里告诉我我理解中的错误吗? 谢谢,汤姆
根据评论,我将内容更改为如下所示:
[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)
{
}
}
这仍然不起作用。 我现在收到一个错误,由于签名不匹配,堆栈不平衡。 我认为字符串正确完成,但 &int 参数可能仍然是一个问题。 汤姆
嗯,我解决了。 这里有一些提示,但没有什么是真正正确的。 在过去几个小时环顾四周后,这是解决方案:
[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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.