Calling C++ code from C# error using references in

2019-07-06 21:28发布

问题:

So in my c++.dll file i got the following function:

    DLL void GetUserPass(char* &userName, char* &passWord)
{
    userName = "ceva";
    passWord = "altceva";
}

Now I want to call this from c# but it gives me an error:

[DllImport("myDLL.dll")]
private static extern void GetUserPass(ref string userName, ref string passWord);

static void f()
{
        string userName ="";
        string passWord ="";

        GetUserPass(ref userName, ref passWord);
}

And the error is:

A call to PInvoke function 'Download FTP Archive!Download_FTP_Archive.Program::GetUserPass' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

Should I try in C++ dll file something like:

using std::string;
 DLL void GetUserPass(string &userName, string &passWord)
{
    userName = "ceva";
    passWord = "altceva";
}

回答1:

try the following:

DLL void __stdcall GetUserPass(char* &userName, char* &passWord)
{
    userName = "ceva";
    passWord = "altceva";
}



[DllImport("myDLL.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
private static extern void GetUserPass(ref IntPtr userName, ref IntPtr passWord);
static void f()
{
        IntPtr userNamePtr = new IntPtr();
        IntPtr passWordPtr = new IntPtr();
        GetUserPass(ref userNamePtr, ref passWordPtr);
        string userName = Marshal.PtrToStringAnsi( userNamePtr );
        string passWord = Marshal.PtrToStringAnsi( passWordPtr );
}


回答2:

I am not a c++ developer, but I am a bit familiar with c++ semantics. This char* &userName makes no sense to me. Maybe I am wrong, but try char* userName and see whether it works for you.



标签: c# c++ dll pinvoke