gpt4 book ai didi

c# - 线程之间以及托管和非托管代码之间的绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 00:57:12 25 4
gpt4 key购买 nike

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

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

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

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

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

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

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

第 3 方程序正常,直到结构中的函数指针从 NULL 更改并且 DLL 中的代码尝试调用它。

最佳答案

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

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

关于c# - 线程之间以及托管和非托管代码之间的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com