2012-05-31 45 views
1

我希望使C++ DLL與C#代碼進行通信,但是我無法讓它工作,我必須從C++ DLL中導入「printf」消息才能在C#的文本框,任何人都可以幫助我,只要它的工作對我來說可以有人指導我嗎?我的主要任務是,在C#就能打印在C++ DLL 的C++ DLL代碼中的「printf」功能,但是這些代碼被編譯爲C:如何將C++ dll printf導入到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) 
     { 

     }   
    } 
+0

考慮使用C++/CLI這種東西。 – Indy9000

回答

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導出你的輸出。否則,它將被截斷。