我正在尝试从C#调用一个非托管DLL。我对非托管代码和P\Invoke的经验很少,所以我希望能有一双额外的眼睛。
除了函数之外,我没有多少关于DLL的信息:
int Initialize(char *FileName, int Driver, int(*InfoLine)(char*), char *Message);Infoline可以为空。
这就是我在C#中所做的。
进口呼叫:
[DllImport(@"c:\Core\initialization.dll", EntryPoint="Initialize", CharSet = CharSet.Auto)]
private static extern int Initialize([MarshalAs(UnmanagedType.LPStr)] string FileName, int Driver, System.IntPtr InfoLine, [MarshalAs(UnmanagedType.LPStr)] string Message);方法调用是:
IntPtr infoLine = IntPtr.Zero;
string message = "";
int success = Initialize(@"c:\config.dat", -1, infoLine, message);Visual在调试模式下返回给我的错误消息是:
对PInvoke函数‘初始化’的调用使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。
我不正确地传递了哪个参数?
我确信对DLL的调用是正确的,因为还有另一个函数没有传递任何参数,并且类似的导入和方法代码可以工作。
谢谢你的帮助。
发布于 2013-08-14 12:43:52
试着加入DllImport(... , CallingConvention=CallingConvention.Cdecl)
有4种将参数传递给“本机”函数的方法。您必须知道哪一个是正确的(将它们放在内存中的位置,谁必须在函数之后从内存中删除它们.)。默认的是StdCall。您的函数可能使用Cdecl。见此处:http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention.aspx
如果/当您决定使用Infoline回调时,
[UnmanagedFunctionPointer(CallingConvenction.Cdecl)]
private delegate int InfolineDelegate(
[MarshalAs(UnmanagedType.LPStr)] string str);
private static extern int Initialize(
[MarshalAs(UnmanagedType.LPStr)] string fileName,
int driver,
[MarshalAs(UnmanagedType.FunctionPtr)] InfolineDelegate infoLine,
[MarshalAs(UnmanagedType.LPStr)] string message);如果Initialize将使用委托,但不会存储它:
Initialize("FileName", 1, MyMethod, "Message");但是,如果Initialize将在稍后的某个时候存储委托以在返回之后使用它:
// Put it outside the function... As a property/field of the class, for example
InfolineDelegate method = MyMethod;
Initialize("FileName", 1, method, "Message");InfolineDelegate method 必须保证的生存期大于您正在使用的方法。所以不是局部变量。通常是调用类的字段/属性。
https://stackoverflow.com/questions/18232083
复制相似问题