C++ and C#

Hi,

This not the unity only question but about learning how to pass code back and forth between C++ and C#.

I was trying to find good tutorials regarding this subject. There are some short videos on youtube , but no in depth explanation. I could not find any Udemy or Pluralsight courses neither.

Do you know good tutorials for interopetability between C# and C++?
I would not mind paying for a good course just there are not any.

I don’t know of any courses, but then again there’s not much to teach really.

The primary keys of note for any native code (C or C++) under Unity are:

  • you’ll be using methods in using System.Runtime.InteropServices;

  • everything is driven as subroutines from Unity to native; you cannot control Unity from native.

  • native code cannot access any of the managed C# data structures directly

  • simple data can just be passed via arguments to native functions

  • managed structured data must be pinned in place, then a reference passed to native functions

  • you may return data from native functions to C#: int, string, bool, etc.

  • strings and structures returned from native must be marshaled back into managed data

  • native code cannot call Unity, except via the UnitySendMessage() call, which actually happens on the next frame

My advice is to structure your interop boundary to be as simple as possible, with as few functions and arguments as possible. A stateful multiplexer can be a huge win here, passing varying commands through a single entrypoint.

I ported all my old MS-DOS and PalmOS games (written in C) to run under Unity, and I use a stateful multiplex system with only a few simple entrypoints.

I wrote up a light technical overview here:

http://plbm.com/?p=20

You can check out KurtMaster2D here:

http://plbm.com/?p=8

2 Likes

I’m confused whether you’re trying to convert code (“pass code back and forth”) between the two languages, or pass data.