Soldier
Soldier

Reputation: 539

How to call C# code in C++

I have a small C# class (Gram.cs) and it is working with a 3rd party dll to operate a device. Now, I need to call some functions in this C# class using C++.

How can I do it?

I am using MS Visual Studio 2010 professional edition.

Upvotes: 3

Views: 11296

Answers (3)

hauron
hauron

Reputation: 4668

This might be what you're looking for (I've answered similiar question here before: how to : use c++ projects for windows phone (C#))

a) Load symbols directly from C library, for example:

using System;
using System.Runtime.InteropServices;
static class win32
{
    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

    [DllImport("kernel32.dll")]
    public static extern bool FreeLibrary(IntPtr hModule);   
}

(this is taken from: http://www.andyrushton.co.uk/csharp-dynamic-loading-of-a-c-dll-at-run-time/ after brief googling)

You need to export the C++ interface methods as "C" for that, e.g.:

extern "C" __declspec( dllexport ) int MyFunc(long parm1);

(from MSDN: http://msdn.microsoft.com/en-us/library/wf2w9f6x.aspx)

b) Use a wrapper in C++/CLI to connect unmanaged C++ to managed C#:

here's a good example: http://www.codeproject.com/Articles/19354/Quick-C-CLI-Learn-C-CLI-in-less-than-10-minutes

Do note that the syntax is somewhat weird at first look, and not eveything can be used. However, what you gain is ability to use the C++ classes - something that exporting "C" prohibits you from doing.

Upvotes: 1

bhavik shah
bhavik shah

Reputation: 593

Normally you should make your c# code as COM visible from your c# project settings and use c# IJW regasm tool.

Look into http://msdn.microsoft.com/en-IN/library/ms173185.aspx

I had integrated c# into c++ using this approach few years ago.

You will be able to load your c# assembly as a COM component in your c++ code.

Upvotes: 2

Lol4t0
Lol4t0

Reputation: 12547

If C# class is small, and it deals with native dll, it might by simpler rewrite that class in C++, rather then integrate .Net into your application. In addition, integrating .Net will force whole .Net virtual machine to start just for processing your simple class.

Otherwise,

  • You could use COM interop: build an assembly based on your C# class and make it COM visible. Then you could use class as a COM-object.
  • You can use Managed C++ to make a wrapper between managed and unmanaged code.
  • You can reverse control flow, so C# code will call unmanaged functions. In this case you can export it from your binary and import from C# code with DllImport attribute.

Upvotes: 3

Related Questions