Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interprocess communication between C# and C++

Tags:

c++

c#

.net

ipc

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 trigger actions).

I don't really want to write my bot in C++, I'm a fairly experienced C# programmer but I have no C++ experience at all. So, the obvious solution is to use ipc to send event to a C# program, and send actions back to the C++ one, that way all I need to write in C++ is a basic framework for calling methods and sending events.

What would be the best way to do this? Sample code would be greatly appreciated as I no have particular desire to learn C++ at this point!

like image 593
Martin Avatar asked Jan 14 '10 12:01

Martin


2 Answers

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.

like image 88
mdm Avatar answered Sep 23 '22 00:09

mdm


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.

like image 40
Aviad P. Avatar answered Sep 19 '22 00:09

Aviad P.