【发布时间】:2016-06-29 12:07:02
【问题描述】:
我正在开发一个 Windows 8 手机应用程序,其中我需要将回调事件消息从 C++ 代码发送到 C# 中的 UI 代码。下面是我在其中创建回调函数并将其指针发送到 C++ 代码的 C# 代码。 C++ 代码可以使用该函数指针向 UI 发送异步事件消息。
C# 代码
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
}
public delegate void CallBack([In][MarshalAs(UnmanagedType.LPStr)] string strParam);
[DllImport("Test.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void PerformActionWithCallBack(int x);
void DemonstrateCallBack()
{
int x;
CallBack callback_delegate = new CallBack(CallBackFunction);
// Converting callback_delegate into a function pointer that can be
// used in unmanaged code.
IntPtr intptr_delegate = Marshal.GetFunctionPointerForDelegate(callback_delegate);
//Getting the pointer into integer value and sending it to C++
x = (int)intptr_delegate;
testApp.PerformActionWithCallBack(x);
}
//CallBack function in which event messages will be received
void CallBackFunction([In][MarshalAs(UnmanagedType.LPStr)] string strParam)
{
if (Dispatcher.CheckAccess() == false)
{
//Updating the text block with the received message
Dispatcher.BeginInvoke(() => MyTextBlock.Text = strParam);
}
else
{
MyTextBlock.Text = "Update directly";
}
}
}
以下是向 C# 发送事件消息的 C++ 代码
//Callback function prototype
typedef void(__stdcall *PCallBack)(LPSTR s);
LPSTR cbMsg = NULL;
//Global instance callback function
PCallBack gUICallback;
void TestApp::PerformActionWithCallBack(int x)
{
//Assigning the received calllback function pointer from C# to global function pointer
gUICallback = (PCallBack)x;
}
//This function will send event messages to C#
void SendCallbackMsg()
{
while(1)
{
cbMsg = "Hello";
Sleep(100);
gUICallback(cbMsg);
cbMsg = "Hi";
Sleep(100);
gUICallback(cbMsg);
}
}
使用此代码,我能够成功地在 C# 中获取事件消息,但是在发送 650-700 个回调后,我的应用程序给出了访问冲突异常,之后没有任何效果。我怀疑我将函数指针从 C# 传递到 C++ 但无法解决它的方式。
【问题讨论】:
标签: c# c++ visual-studio windows-ce