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

只谈情不闲聊 提交于 2019-12-23 20:32:52

问题


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.



来源:https://stackoverflow.com/questions/10681887/calling-c-code-from-c-sharp-error-using-references-in-c-ref-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!