从C ++传递到C#的字符串打印空白

时间:2016-07-31 18:39:44

标签: c# c++ c++11 visual-c++

#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
}

我不是C#guy.I在发布之前做了一些阅读,并尝试了所有可能的组合,但有些原因它没有用。我使用的是Visual Studio 2013.I有几个Q

[Q1]当我做MessageBox.Show(strErr.ToString());在我的C#中,它只打印一个空白字符串!如果有人能帮助我,我将非常感激,因为我对这一切都很陌生。

[Q2]如果我给EntryPoint =“Server”我的代码不起作用。它抱怨,在Hello.dll中找不到服务器的enrty点。所以,每次我必须使用dumpbin.exe在我的dll中找到确切的条目,然后确切地提供编译器为我创建的方式

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

是否有更好的方法可以做到这一点。这就是使代码变得黯然失色

[Q3]有没有办法调用C ++构造函数/析构函数。我确实需要调用它们。我已经通过其他方法调用了C'tor,我知道这不是一个好主意。任何帮助将不胜感激

感谢。

1 个答案:

答案 0 :(得分:0)

我不认为它与静电有关。这完全是关于对象的正确分配。从其他C ++调用时,同一段代码完全正常。我稍微调整了一下代码。现在,我使用strcpy_s并且它正在工作,因为在破坏数据的同时,我正在丢失数据。

我还在等待Q2回答。