0

我有一个在第 3 方程序中使用的 C++ dll(特别是 directshow 过滤器)。我通过共享内存使用 C# 程序来控制它(所以在 C# 端使用 MemoryMappedFile,在 C++ 端使用 CreateFileMapping)。

所以要清楚:没有1个程序。它是同时运行 2 个不同的程序,我希望非托管代码 (C++) 程序调用托管代码程序 (C#) 中的方法

内存共享工作正常。我可以使用 C# 程序来更改和检查值,因为第 3 方程序使用 dll。

问题是我想有效地将​​我的 C# 程序的某些方面数据绑定到 C++ dll 中的值。也就是说,当第 3 方程序使用的 dll 中的值发生更改时,我希望它在 C# 程序中自动更新。

现在我当然可以在我的 C# 程序的另一个线程中每秒轮询一次值。但我想要的是让我的 dll 在 C# 中调用 PropertyChangedEventHandler。或者至少调用一个调用它的方法。

我的第一种方法是通过共享内存通过 IntPtr 传递 C# 方法的委托。

所以 C++ 查看共享内存,它看到了一个像这样的结构

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
}

我的 C# 代码查看共享内存并看到

struct MyStruct
{
    //...the same ints as in the C++
    public IntPtr ptr2Func;
    //etc..
}

正如我所说,共享内存结构中的所有其他值都可以正常工作,我可以手动检查以查看或修改值。

当 C++ dll 的主进程初始化时,它将 ptr2Func 设置为 NULL。然后在尝试执行它之前确保它不为 NULL。

然后 C# 将其设置为本地方法:

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);

在结构中的函数指针从 NULL 更改并且 DLL 中的代码尝试调用它之前,第 3 方程序很好。

4

1 回答 1

3

我不认为你可以做到这一点,基本上。这两个进程在不同的地址空间中运行。您存储在共享内存中的地址确实指向 C# 进程中的函数,但它不指向调用进程的代码。它只会崩溃。

您可以使用 WCF、命名管道或套接字将触发消息发送到其他应用程序。

于 2012-05-04T17:30:52.017 回答