我希望使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)
        {

        }
    }

最佳答案

不要使用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导出中输出的任何消息。否则,它将被截断。

09-09 23:52
查看更多