Guy
Guy

Reputation: 67230

Can you call a C# DLL from a C DLL?

I've built a DLL in C#. Now I want to use the R Environment to call functions in that DLL. The R environment supports calling unmanaged C/C++ DLL's but not into .NET DLL's. So my question is, can I call functions in a C# DLL from a C/C++ DLL? If so, do you have a link to info about how to do this?

Upvotes: 8

Views: 9273

Answers (3)

Rob Deary
Rob Deary

Reputation: 997

It is actually pretty easy. Just use NuGet to add the "UnmanagedExports" package to your .Net project. See https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports for details.

You can then export directly, without having to do a COM layer. Here is the sample C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RGiesecke.DllExport;

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int left, int right)
    {
        return left + right;
    }
}

R should be able to load TextExport just like a regular C dll.

Upvotes: 1

Kev
Kev

Reputation: 119806

This article might help you out:

CLR Hosting APIs (MSDN)

Updated: There's a tool called mergebin that ships with the .NET SQLite wrapper you can use to create a mixed mode native/managed DLL. Grab the source code from:

SQLite for ADO.NET 2.0 (SourceForge)

You'll find the exe in the bin\tools folder.

Kev

Upvotes: 3

Andy
Andy

Reputation: 30418

The most straight forward way of doing this is to expose one of the C# classes in your C# DLL as a COM object, and then create an instance of it from your C/C++ DLL. If that isn't an acceptable option, you'd need to create a mixed-mode C++ DLL (which contains both managed and unmanaged code). Your C/C++ DLL can call exported functions in your mixed-mode DLL, which can in turn forward the calls on to your C# class.

Upvotes: 9

Related Questions