抱歉,这个问题太笼统了,但是我想知道什么是最佳解决方案。
我有两个项目。主要的代码位于C ++中,需要从软件组件接收一些信息。为此,它使用了我在C#中编写的.NET dll,并使用.NET库从软件组件接收信息。我将编写一个简单的CLI项目以获取我的C#项目获得的信息。
因此,我的问题是C#项目对事件的预订很多,需要从软件组件异步接收信息。因此,我不知道如何在C ++中触发操作(我的主项目使用此.NET dll从软件组件中请求信息)来保存当时已收集的所有数据。
例如,我在C#项目中拥有此事件订阅:
private void SubscribeMessages()
{
comm.Comms.Subscribe(new Action<LoadFilterEVENTMessage>(LoadFilterEVENT));
}
private void LoadFilterEVENT(LoadFilterEVENTMessage msg)
{
FilterValue = msg.Filter;
}
因此,我希望这个LoadFilterEVENT让C ++知道它已经具有过滤器值。有提示吗?
非常感谢您:)
这里有一个解决方案:
1-您的C#dll需要加载C ++ SubscribeMessages DLL,它将使用方法DispatchEvents
通知程序。
using System.Runtime.InteropServices; namespace MyCSharpDLL { class PlatformInvokeTest { // Import C++ DLL [DllImport("SubscribeMessages.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void DispatchEvents(); static void LoadFilterEVENT(/*LoadFilterEVENTMessage msg*/) { //FilterValue = msg.Filter; DispatchEvents(); } /* Methods in DLL being used below */ public static void Main() { LoadFilterEVENT(); } }; }
2-函数
DispatchEvents
的作用是释放二进制信号量以解锁C ++程序:
中,这为您的程序提供了更大的灵活性:extern "C" __declspec(dllexport) void DispatchEvents() { // Juste open Semaphore HANDLE ghSemaphore = OpenSemaphore (SEMAPHORE_ALL_ACCESS , TRUE, _T("SemSubscribeMessages")); if ( NULL == ghSemaphore) { MessageBox(NULL,_T("Error when opening semaphore"),_T("Error"),0); return; } // Release semphare in order that CPP program can be notified ReleaseSemaphore(ghSemaphore, 1, NULL); }
最后,您的C ++程序必须等待
SemSubscribeMessages
信号量才能接收通知。由于等待的阻塞,我将WaitForSingleObject
函数放在单独的thread
#include <windows.h> #include <iostream> using namespace std; // Init value = 0 to block on the first call #define INITIAL_COUNT 0 // Max value 1 to be a binarySemaphore #define MAX_SEM_COUNT 1 DWORD WINAPI ListenNewEvent (LPVOID lpParam ) { DWORD dwWaitResult; HANDLE ghSemaphore = CreateSemaphore( NULL, INITIAL_COUNT, MAX_SEM_COUNT, _T("SemSubscribeMessages")); if ( NULL == ghSemaphore) return -1; while (true) { cout<< _T("Wainting for new Events ...")<<endl; dwWaitResult = WaitForSingleObject( ghSemaphore, INFINITE); MessageBox(NULL,_T("New Event arrive ..."),NULL,0); } } int _tmain(int argc, _TCHAR* argv[]) { DWORD dwThreadId; HANDLE hListnerThread = CreateThread( NULL, 0, ListenNewEvent, NULL, 0, &dwThreadId); WaitForSingleObject (hListnerThread, INFINITE); return 0; }
如果您还需要共享数据(除了事件之外),则可以在通知后添加“共享内存”层,希望对您有所帮助