2

Is there any C# interpreter that can be used inside C++ and yet still allow .Net access?
I want to use C# scripts for games and I'm not sure how to proceed with that.

Sanctus2099
  • 1,669
  • 5
  • 22
  • 40

7 Answers7

5

You can write a simple class in C#, let's call it ScriptRunner that would take your C# code as input, compile it at runtime to produce a new assembly in memory, then it will use Reflection to load a specific Type from this new assembly, and will run some method with an expected name.

Then, use COM Interop (for example) to create a ScriptRunner .NET object from your C++ native application, and you'll be able to use it to run scripts.

Start with:

var myProvider = Microsoft.CSharp.CSharpCodeProvider.CreateProvider();
var myCompiler = myProvider.CreateCompiler();

and it's really easy to continue on your own by using IntelliSense to see what's on the ICodeCompiler interface.

If you've got some specific questions about this approach please ask.

Ran
  • 5,989
  • 1
  • 24
  • 26
2

C# is not an interpreted language, it is a compiled language.

You can write C# scripts, but why not use Python or Ruby or Lua or some other true-blue scripting language?

I feel somewhat dirty mentioning this, but it looks like there is an ECMA compliant C# scripting engine.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
  • These are thin lines. C# is interpreted on .NET Micro. Python, Ruby and Lua are compiled. There are jitters for Python and (I think) Ruby. – Hans Passant Dec 09 '10 at 21:00
  • 2
    Some people just really like C#'s syntax. I much prefer languages that use curly brackets anyway, though I do get your point. :) – JC Leyba Dec 09 '10 at 21:08
0

I believe C# is a compiled language only. Your best bet would be to call the csharp compiler (csc.exe) and load the assembly dynamically.

Brian Ball
  • 12,268
  • 3
  • 40
  • 51
0

YOu can have .net dlls and use them in your C++ code.

pavanred
  • 12,717
  • 14
  • 53
  • 59
0

Is it C++ or C++/CLI? If it's the "normal" C++ I don't think it will be possible to use C# as it is a compiled language and a managed one, your best bet would be to use the managed version of C++ and compile the C# code, then load it.

0

I've never tried to do that but I think C# is definitely not a suitable language for scripting, for your purpose Lua or Python (for example) are certainly better...

AFract
  • 8,868
  • 6
  • 48
  • 70
0

I assume you want to use C++ for DirectX/OpenGL support and then want to load in the entire .Net Framework on top of that to support scripting? That would be a very heavy footprint if it were possible. Since C# is compiled into bytecode (just like Java), you would have to precompile your scripts.

Your best best is to to use an opensource scripting language (php, lua, etc).

Zac Howland
  • 15,777
  • 1
  • 26
  • 42