我希望使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 %ldn", 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(): %ldn", WSAGetLastError());
// Clean up
WSACleanup();
// Exit with error
return -1;
}
else
{
printf("Server: socket() is OK!n");
}
}
}
这是 C# 代码,我尝试导入 DLL C++有人可以指出我应该如何处理由我的代码制作的示例代码:
public partial class Form1 : Form
{
[DllImport(@"C:UsersDocumentsVisual Studio 2010ProjectsServer_Receiver Solution DLLDebugServer_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 导出输出的任何消息。否则,它将被截断。