dimanche 31 juillet 2016

string passed from C++ to C# prints blank

#ifdef SERVER_TCP_EXPORTS
class __declspec(dllexport) Sock_Server
#else
class __declspec(dllimport) Sock_Server
#endif
{
public:
    int Server(const char* strErr,int bufSize);
    ...
 }

cpp file
int Sock_Server::Server(const char* strErr,int bufSize)
{
   // do something and assign the string to strErr
   (say) strErr = "Hello World";
   return -1;
}

in C#
[DllImport("Hello.dll", EntryPoint = "Server" CallingConvention = CallingConvention.StdCall)]

private extern static int Server(StringBuilder strErr, int bufSize);

public static int Connect(StringBuilder strErr, int bufSize)
{
   int res = Server(strErr,bufSize);    /// when the calls come here, strErr is empty
    return res;          // res has the value  -1
}

private void Form1_Load(object sender, EventArgs e)
{
   int res = 0;
   int bufSize = 4096;
   StringBuilder strErr = new StringBuilder(bufSize+1);

   res = Connect(strErr, bufSize); //when the calls come here, strErr is empty
    MessageBox.Show(strErr.ToString());   // it has the value -1
}

I am not a C# guy.I did some reading before posting this out,and tried all the possible combinations but some reason it didn't work.I am using Visual Studio 2013.I have couple of Q

[Q1] When I did MessageBox.Show(strErr.ToString()); in my C#, it just prints a blank string! Would really appreciate if anyone can help me as I am pretty new to all this.

[Q2] If I give EntryPoint ="Server" my code doesn't work.It complains,enrty point of Server is not found in Hello.dll. So,every time I have to find the exact entry in my dll using dumpbin.exe and then provide exactly how the compiler has created for me

[DllImport("Hello.dll", EntryPoint = "?Server@Sock_Server@@QAEHPBDH@Z" CallingConvention = CallingConvention.StdCall)]

Is there a better way of doing this.This is making the code cupled

[Q3] Is there a way to call C++ constructor/destructor.I do need to call both of them.I have called C'tor through some other method,I know that's not a good idea.Any help would be appreciated.

Thanks.

Aucun commentaire:

Enregistrer un commentaire