简体   繁体   English

如何使用C#中的PInvoke强制参数计数为dll函数

[英]How to enforce arguments count to dll function using PInvoke in C#

I have written a C dll containing a function that takes 4 arguments and returns a number. 我编写了一个包含函数的C dll,它接受4个参数并返回一个数字。 Then I created a C# application and called the dll function using PInvoke. 然后我创建了一个C#应用程序并使用PInvoke调用了dll函数。 Everything works fine. 一切正常。 Then I changed no of arguments in the dll function from 4 to 3. But I did not change the method signature (DllImport method signature) in C#. 然后我在dll函数中将参数从4更改为3.但是我没有在C#中更改方法签名(DllImport方法签名)。 To my surprise, the call still succeeds from C# but I get some unexpected value returned from the dll function. 令我惊讶的是,调用仍然来自C#,但我从dll函数返回了一些意外的值。

I was expecting an exception but the call went through. 我期待一个例外,但电话通过了。 Is there any way to strictly enforce arguments count when making function calls using P/Invoke? 在使用P / Invoke进行函数调用时,有没有办法严格执行参数计数?

There is no way to enforce parameter count to match. 无法强制参数计数匹配。 You simply have to get it right. 你只需要做对。 The same is true for calling convention, parameter types and so on. 调用约定,参数类型等也是如此。

Unlike managed code, native DLLs do not have metadata describing how they must be called. 与托管代码不同,本机DLL没有描述必须如何调用它们的元数据。

If you enable the p/invoke stack imbalance MDA then you will at least be able to detect the error you made at runtime. 如果启用p / invoke堆栈不平衡MDA,那么您至少可以检测到您在运行时所犯的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM