• Advertisement
Sign in to follow this  

Calling C++ code from C#

This topic is 2260 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement