【发布时间】:2014-06-18 10:54:58
【问题描述】:
我有一个 dll 必须与不是用 C# 编写的程序通信。我已经用这段代码建立了这种联系:
namespace ClassLibrary1
{
public class Class1
{
[DllExport("teststring", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.BStr)]
public static String TestString(string test)
{
return "Test" + test;
}
public static CallbackProc _callback;
[DllExport("SetCallback", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
public static void SetCallback(CallbackProc pCallback)
{
_callback = pCallback;
//var app = new App();
//var win = new MainWindow();
//app.Run(win);
MessageBox.Show("C#: SetCallback Completed");
}
[DllExport("TestCallback", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
public static void TestCallback(string passedString)
{
string displayValue = passedString;
string returnValue = String.Empty;
TodayButton.MainWindow app = new TodayButton.MainWindow();
app.InitializeComponent();
MessageBox.Show("C#: About to call the Callback. displayValue=" + displayValue + ", returnValue=" + returnValue);
_callback(displayValue, ref returnValue);
MessageBox.Show("C#: Back from the Callback. displayValue=" + displayValue + ", returnValue=" + returnValue);
}
public delegate void CallbackProc( [MarshalAs(UnmanagedType.BStr)] String PassedValue, [MarshalAs(UnmanagedType.BStr)] ref String ReturnValue);
}
}
所以回调工作完美。我有一个问题,我不知道如何解决。
我想将其用作我的 WPF 应用程序的界面。因此,当程序调用 dll 时,dll 应该启动 WPF 应用程序并等待该应用程序关闭并发送信息,然后我会调用回调。
问题是我不想在每次需要信息时启动和停止 WPF 应用程序。我想要一个按钮“发送到回调”。问题是这个项目是一个类库,使用 DllExport 并且 WPF 项目不会编译为类库。
有没有办法做到这一点,所以我可以用 dll 控制整个 WPF 应用程序?所以我将控制开始、停止、传递回调值,以便我可以从 WPF 表单中调用它们,或者当我按下 WPF 中的按钮时将信息发送回TestCallback 函数。
这怎么可能?
【问题讨论】: