C# Integration with Other Languages: From P/Invoke to Python and JavaScript

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why C# Doesn't Live in a Vacuum, and How It Works

\n\n

When I started working with C# about ten years ago, it seemed to me that .NET was a self-sufficient universe. Libraries, frameworks, databases — everything at hand. But then a task came up: I needed to use an old C++ library for signal processing. And then I realized — C# integration with other languages is not a luxury, but a necessity for any serious project.

\n\n

Today, C# is a cross-platform language with a rich ecosystem, but it can't do everything. Sometimes you need to run a Python script for machine learning, sometimes you need to call a native function from Rust for maximum performance, and sometimes you need to embed a JavaScript engine for dynamic UI generation. The good news: C# can be friends with almost everyone.

\n\n

In this article, I will show real scenarios of C# interaction with other languages with working code, benchmarks, and pitfalls. Let's go!

\n\n

P/Invoke: The Classic for C and C++

\n\n

Platform Invocation Services (P/Invoke) is a built-in .NET mechanism for calling functions from native DLLs. It appeared in the first version of .NET and remains the fastest way to integrate with C/C++ code.

\n\n

Basic Example: Calling a Function from C

\n\n

Suppose we have a native library math_helper.dll with a function:

\n\n
// math_helper.h\nextern "C" __declspec(dllexport) double calculate_power(double base, int exp);
\n\n

In C#, we connect it like this:

\n\n
using System.Runtime.InteropServices;\n\npublic class NativeMath\n{\n    [DllImport("math_helper.dll", CallingConvention = CallingConvention.Cdecl)]\n    public static extern double calculate_power(double base, int exp);\n}\n\n// Usage\ndouble result = NativeMath.calculate_power(2.0, 10);\nConsole.WriteLine($"2^10 = {result}"); // 1024
\n\n

Important points for P/Invoke C#:

\n
    \n
  • Always specify CallingConvention — most often Cdecl or StdCall.
  • \n
  • For strings, use MarshalAs(UnmanagedType.LPStr) or LPWStr.
  • \n
  • Pass structures by reference using ref or out.
  • \n
\n\n

P/Invoke provides minimal overhead — literally a few nanoseconds per call. If you need to integrate C# with C++ for high-load computations, this is your choice.

\n\n

C++/CLI: The Bridge Between Worlds

\n\n

C++/CLI is a Visual C++ extension that allows you to write code that works in both managed (.NET) and unmanaged environments. It's not a separate language, but a hybrid often used to create wrappers around C++ libraries.

\n\n

Example Wrapper for OpenCV

\n\n

Suppose we have a C++ function that processes an image:

\n\n
// NativeImageProcessor.h\n#pragma once\npublic ref class ImageProcessor\n{\npublic:\n    static System::Drawing::Bitmap^ ApplyFilter(System::Drawing::Bitmap^ bmp);\n};
\n\n

Inside, we call native OpenCV, and externally we return a managed Bitmap. From C#, we use it like a regular .NET library:

\n\n
using ImageProcessorLib;\n\nvar img = new Bitmap("photo.jpg");\nvar processed = ImageProcessor.ApplyFilter(img);\nprocessed.Save("filtered.jpg");
\n\n

C++/CLI integration gives full control over memory and avoids marshaling. The downside is that the code becomes platform-dependent and harder to debug.

\n\n

Python.NET: Calling Python from C#

\n\n

Python is the king of Data Science and machine learning. And if your C# project requires, say, running a neural network on PyTorch or processing text via spaCy, calling Python from C# via Python.NET is what you need.

\n\n

Installation and First Example

\n\n

Install the package:

\n\n
dotnet add package Python.Runtime.NETStandard

Blogs

Book Recommendations