0

I am working on a basic 2D C++ Game engine but i want to be able to use C# to make games with it like unity does but I'm not sure how to do it. I've seen people saying about CLI but not sure exactly how that works. I want to be able to access functions on the engine in C# and be able to have the engine run the C# code.

Thanks for any help with this.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
RadiantMin3
  • 103
  • 1
  • 8
  • 1
    You probably should change your question title to something like: Using c# code from a native c++ application. You are not trying to spawn a c# compiler from your c++ application to build some unrelated c# project. With this said I am not sure this is an on-topic request. You basically want a tutorial. – drescherjm Jun 23 '20 at 17:33
  • There's a difference between a tutorial and just a name for the thing you're trying to do. It's hard to search something if you don't even know what it's called. – Blindy Jun 23 '20 at 17:38
  • Where do you want `main` to be in? Your C# EXE which loads your game engine? Or does your game engine have its own EXE and `main` and loads you game logic from a .NET assembly? – selbie Jun 23 '20 at 17:39
  • Check this SO thread. P\Invoke or CLI for native managed communication. https://stackoverflow.com/questions/2561898/p-invoke-or-c-cli-for-wrapping-a-c-library – Sisir Jun 23 '20 at 17:40

1 Answers1

5

Right now you have two big ways of doing this:

  1. Make your C# application generate COM objects which you can consume from C++. Performance is a bit iffy, but doable and very simple.

  2. Use reverse PInvoke, where you export functions from your C++ application with in function pointers that you fill in from the C# side with delegates to the functions that drive your code.

In .Net 5, there's a third way: you can directly export C# functions from your assemblies to be consumed in a platform-independent way, like in C++ (ie, .dll or .so exports).

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • Would it be best to run the game from the engine or have the game use what it needs from the engine? – RadiantMin3 Jun 23 '20 at 17:46
  • 1
    Generally the engine is the game, so I don't really know what you mean, but if you're asking which side should drive the application, C++ or C#, in an ideal world it's up to you. Right now it's a bit easier to drive it from C#, but in .Net 5 it's just as easy either way! – Blindy Jun 23 '20 at 17:54