Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

dll

pinvoke

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";
}
like image 664
Thanatos Avatar asked May 13 '26 04:05

Thanatos


1 Answers

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 );
}
like image 113
smerlin Avatar answered May 14 '26 17:05

smerlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!