Interprocess communication between C# and C++

前端 未结 3 1358
悲哀的现实
悲哀的现实 2021-02-06 00:03

I\'m writing a bot for a game, which has a C++ API interface (ie. methods in a Cpp dll get called by the game when events occur, the dll can call back methods in the game to tri

相关标签:
3条回答
  • 2021-02-06 00:30

    There are lots of different ways of doing IPC in Windows. For C# to C++, I'd be tempted to use Sockets as the API under both C++ (WinSock is OK once you get your head around it) and C# is pretty easy.

    Named Pipes might be better though if you don't want to use sockets, and were designed specifically for IPC. The API under C++ seems pretty simple, example here.

    0 讨论(0)
  • 2021-02-06 00:44

    In such occasion, I would like to see a C++/CLI party and a C# one using the .NET Framework's named pipes.

    0 讨论(0)
  • 2021-02-06 00:51

    One solution is to create a managed C++ class library with regular __declspec(dllexport) functions which call managed methods in a referenced C# class library.

    Example - C++ code file in managed C++ project:

    #include "stdafx.h"
    
    __declspec(dllexport) int Foo(int bar) 
    {
        csharpmodule::CSharpModule mod;
        return mod.Foo(bar);
    }
    

    C# Module (separate project in solution):

    namespace csharpmodule
    {
        public class CSharpModule
        {
            public int Foo(int bar)
            {
                MessageBox.Show("Foo(" + bar + ")");
                return bar;
            }
        }
    }
    

    Note that I am demonstrating that this is an actual .NET call by using a System.Windows.Forms.MessageBox.Show call.

    Sample basic (non-CLR) Win32 console application:

    __declspec(dllimport) int Foo(int bar);
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        std::cout << Foo(5) << std::endl;
        return 0;
    }
    

    Remember to link the Win32 console application with the .lib file resulting from the build of the managed C++ project.

    0 讨论(0)
提交回复
热议问题