简体   繁体   中英

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++ class looks like:

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

Defined in C# like this:

 [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. 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.

If you want to use C++ class in C#, you need to go with 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. 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. It will be a very flexible soltuion which is easy to expand. On MSDN you can find examples how to use C++/CLI.

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.

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