Skip to main content
gamedev.net
🔒 Locked

Calling C++ code from C#

Started by 3DModelerMan 1 reply 1.4k views
Original Post
3DModelerMan
3DModelerMan
I want to write my game editor in C#, the problem is, my engine is written in C++. I know that you can call DLL functions from your C++ engine, and I know how. Is there a better way? Some way that allows calling C++ classes from C#? SWIG wraps C++ code to C#, but what do I need to do to call the generated wrappers?
Nypyren
Nypyren
If you write a C++/CLI wrapper project, that project can #include and link in "plain" C++ code, and will result in a .Net DLL, with classes and everything. You will need to create "gc class" wrappers for the native C++ classes that you want to use from C#. The end result is very convenient, but sometimes wrapping the native C++ class inside a C++/CLI wrapper can be pretty tricky.

I usually use this approach, but I've only done this for non-game projects so far.

I've never used SWIG, so I don't know if it automates this or takes a different approach.
NightCreature83
NightCreature83

If you write a C++/CLI wrapper project, that project can #include and link in "plain" C++ code, and will result in a .Net DLL, with classes and everything. You will need to create "gc class" wrappers for the native C++ classes that you want to use from C#. The end result is very convenient, but sometimes wrapping the native C++ class inside a C++/CLI wrapper can be pretty tricky.

I usually use this approach, but I've only done this for non-game projects so far.

I've never used SWIG, so I don't know if it automates this or takes a different approach.


This is exactly the way most tool pipelines, that need some major part of a C++ engine to run interface with it. The C++/CLI wrapper will handle all of the marshaling of data for you, in either direction. The wrapper classes will be visible to the C# app and all of the C++ is visible to the native code.


Be careful however that when you define a ref class you cannot allocate native memory as C# is able to interact with this class.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.