简体   繁体   中英

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.

I have a C++ .DLL file injected into memory. Although, this DLL simply fetches information from the application and also gets information from the C# .exe.

The C# exe information will change every second, while the C++ information will change only once or twice.

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. Keep types of parameters as simple as possible. Any C# thread can make these calls.
  2. Start your own C++ threads that read/modify only the C++ data and call only the C++ methods and functions.
  3. Use Windows kernel objects for synchronization and other similar stuffs. 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.

To call a C++ finction, add to your assembly:

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

This tells that User32 has and entry point MessageBeep that your want to call. 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.

I will be using a named pipe so the two processes can communicate together easily! (C# server and C++ Client)

Thanks for the help everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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