简体   繁体   English

从C#传递到非托管dll后,参数不正确

[英]Parameters are incorrect after passing from C# to unmanaged dll

Have been trying all day and searching various sources but can't find a solution. 整天都在尝试并搜索各种资源,但找不到解决方案。 I am calling an imported unmanaged dll function from c#. 我正在从c#调用导入的非托管dll函数。

C++ class looks like: C ++类如下所示:

class  MyModule
{
public:
    MYMODULEDLL_API int __cdecl Init(int);
...

Defined in C# like this: 在C#中定义如下:

 [DllImport("MyModule_x64.dll", EntryPoint = 
  "?Init@MyModule@@QEAAHH@Z", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Init(int len);

And calling like this: 像这样调用:

Init(configFileName.Length);

I can see in the debugger that the proper function in the dll is being called, but the passed parameter is corrupted showing a completely different value than what was passed. 我可以在调试器中看到正在调用dll中的适当功能,但是传递的参数已损坏,显示的值与传递的值完全不同。 This is happening for string parameters as well. 字符串参数也会发生这种情况。 Is there anyway to troubleshoot the marshalling of parameters between managed and unmanaged code? 无论如何,要解决托管代码和非托管代码之间的参数编组问题吗?

You can`t use C++ classes using DLLImport or PINVOKE, because it is suitable only for C style functions. 您不能通过DLLImport或PINVOKE使用C ++类,因为它仅适用于C样式函数。

If you want to use C++ class in C#, you need to go with C++/CLI. 如果要在C#中使用C ++类,则需要使用C ++ / CLI。 You can create an unmanaged dll in native C++ and then create a simple C++/CLI wrapper which calls methods from native dll. 您可以在本机C ++中创建一个非托管dll,然后创建一个从本机dll调用方法的简单C ++ / CLI包装器。 After that you can simply add a C++/CLI managed dll to the project and use it as C# class without any DllImports and PINVOKEs. 之后,您可以简单地将C ++ / CLI托管dll添加到项目中,并将其用作C#类,而无需任何DllImport和PINVOKE。 It will be a very flexible soltuion which is easy to expand. 这将是一个非常灵活的解决方案,易于扩展。 On MSDN you can find examples how to use C++/CLI. 在MSDN上,您可以找到有关如何使用C ++ / CLI的示例。

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

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