I have a C++ dll (specifically a directshow filter) which is being used in a 3rd party program. I am controlling it with a C# program via shared memory (so MemoryMappedFile on the C# side, and CreateFileMapping on C++).
So to be clear: There is not 1 program. It is 2 different programs running at once, and I want the unmanaged code (C++) program to invoke a method in the managed code program (C#)
The memory sharing works fine. I can use the C# program to change and check values as the 3rd party program uses the dll.
The problem is that I want to effectively databind some aspect of my C# program to a value in the C++ dll. That is, when ever the value is changed in the dll being used by the 3rd party program, I want it to automagically update in the C# program.
Now I can certainly just poll the value every second in another thread of my C# program. But what I would like is to have my dll call a PropertyChangedEventHandler in C#. Or at least call a method that invokes it.
My first approach was to pass a delegate of a C# method through an IntPtr via the shared memory.
So the C++ looks at the shared memory and it sees a struct like so
struct MyStruct
{
//...some ints, etc
int (*ptr2Func)(int); //not sure if I need to change this to a void pointer, but then how do I cast it to a function pointer in my C++?
//...etc
}
my C# code looks at the shared memory and sees
struct MyStruct
{
//...the same ints as in the C++
public IntPtr ptr2Func;
//etc..
}
As I said, all the other values in the shared memory struct work fine and I can manually check to see or modify values.
When the C++ dll’s main process is initialized, it sets the ptr2Func to NULL. It then makes sure it’s not NULL before it tries to execute it.
The C# then sets it to a local method:
unsafe public delegate int mydelegate(int input);
public myDelegate tempDele;
public int funcToBeCalled(int input)
{
return (2);
}
// this code is inside a button click method right after it connects the C# program to the shared memory:
tempDele = this.funcToBeCalled;
sharedInstanceOfMyStruct->pt2Func = Marshal.GetFunctionPointerForDelegate(tempDele);
The 3rd party program is fine until the function pointer in the struct is changed from being NULL and the code in the DLL tries to call it.
I dont think you can do this, basically. The two processes are running in a different adress space. The adress that you store in your shared memory does point to a function in the C# process, but it does not point to code the calling process. It will just crash.
You can use WCF, named pipes or sockets to send a trigger message to the other application.