1

我希望使 C++ DLL 与 C# 代码进行通信,但我无法让它工作,我必须从 C++ DLL 导入“printf”消息才能在 C# 文本框中打印,只要有谁能帮我解决这个问题它工作对我来说很好,有人可以指导我吗?我的主要优先事项是 C# 将能够在 C++ DLL 中打印“printf”函数 C++ DLL 代码,但代码被编译为 C:

ReceiverInformation()
{
     //Initialize Winsock version 2.2
     if( WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
     {
          printf("Server: WSAStartup failed with error %ld\n", WSAGetLastError());
          return -1;
     }
     else
     {
         printf("Server: The Winsock DLL status is %s.\n", wsaData.szSystemStatus);
         // Create a new socket to receive datagrams on.
         ReceivingSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

         if (ReceivingSocket == INVALID_SOCKET)
         {
              printf("Server: Error at socket(): %ld\n", WSAGetLastError());
              // Clean up
              WSACleanup();
              // Exit with error
              return -1;
         }
         else
         {
              printf("Server: socket() is OK!\n");
         }
     }
}

这是 C# 代码,我尝试导入 C++ DLL 有人可以指出我应该如何处理由我的代码制作的示例代码:

public partial class Form1 : Form
    {
        [DllImport(@"C:\Users\Documents\Visual Studio 2010\Projects\Server_Receiver Solution DLL\Debug\Server_Receiver.dll", EntryPoint = "DllMain")]
        private static extern int ReceiverInformation();

        private static int ReceiverInformation(IntPtr hWnd)
        {
            throw new NotImplementedException();
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //textBox1.Text = "Hello";
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }           
    }
4

1 回答 1

1

不要使用printf. 将您的字符串传递给 C#。像这样:

C++ DLL 代码片段如下:

extern "C" __declspec(dllexport) int Test(char* message, int length)
{
    _snprintf(message, length, "Test");
    return 1;
}

C# 片段如下:

[DllImport(@"test.dll")]
private static extern int Test(StringBuilder sb, int capacity);

static void Main(string[] args)
{
    var sb = new StringBuilder(32);
    Test(sb, sb.Capacity);

    // Do what you need here. In your case, testBox1.Text = sb.ToString()
    Console.WriteLine(sb);
}

确保您StringBuilder的容量可以适合您从 DLL 导出中输出的任何消息。否则,它将被截断。

于 2012-05-31T04:47:09.980 回答