简体   繁体   English

在C#和C之间共享变量

[英]Sharing variable between C# and C

I've seen a few answers for almost the same question, but there wasn't C# code to help me understand. 我已经看到了几乎相同问题的一些答案,但是没有C#代码可以帮助我理解。

I have a C++ .DLL file injected into memory. 我有一个C ++ .DLL文件注入到内存中。 Although, this DLL simply fetches information from the application and also gets information from the C# .exe. 虽然,此DLL只是从应用程序中获取信息,还从C#.exe获取信息。

The C# exe information will change every second, while the C++ information will change only once or twice. C#exe信息将每秒更改一次,而C ++信息将仅更改一次或两次。

How can I create a shared variable between the two running applications, and how can I read/write to it? 如何在两个正在运行的应用程序之间创建共享变量,以及如何对其进行读写?

Thank you! 谢谢!

If you want to build a reliable solution, you should use the following: 如果要构建可靠的解决方案,则应使用以下方法:

  1. Calls from C# to C++ functions. 从C#到C ++函数的调用。 Keep types of parameters as simple as possible. 保持参数类型尽可能简单。 Any C# thread can make these calls. 任何C#线程都可以进行这些调用。
  2. Start your own C++ threads that read/modify only the C++ data and call only the C++ methods and functions. 启动您自己的C ++线程,这些线程仅读取/修改C ++数据并仅调用C ++方法和函数。
  3. Use Windows kernel objects for synchronization and other similar stuffs. 使用Windows内核对象进行同步和其他类似的工作。 It is fine when one side signals the event and the other side waits for it. 一方发出事件信号而另一方等待事件就很好了。

Other types of interaction are possible but I would discourage from using them. 其他类型的交互也是可能的,但我不鼓励使用它们。 These additional types are not simple and not that clearly defined, contain caveats, etc. The 3 methods above allow building complex applications. 这些附加类型并不简单,定义也不明确,包含警告等。上述3种方法允许构建复杂的应用程序。

To call a C++ finction, add to your assembly: 要调用C ++函数,请添加到程序集中:

[DllImport("User32.dll")]
static extern Boolean MessageBeep(UInt32 beepType);

This tells that User32 has and entry point MessageBeep that your want to call. 这表明User32具有您要调用的入口点MessageBeep After that you can use it as any other function: 之后,您可以将其用作任何其他功能:

MessageBeep(0);

In a similar way you can call GetProcAddress or any other entry point in your own DLL. 您可以通过类似的方式在自己的DLL中调用GetProcAddress或任何其他入口点。

I will be using a named pipe so the two processes can communicate together easily! 我将使用命名管道,以便两个进程可以轻松地相互通信! (C# server and C++ Client) (C#服务器和C ++客户端)

Thanks for the help everyone! 感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM