8

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?

Guy
  • 65,082
  • 97
  • 254
  • 325

3 Answers3

9

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.

Andy
  • 30,088
  • 6
  • 78
  • 89
  • That mixed mode C++ DLL sounds like it would do the trick - I've just had a look at the templates available to create a mixed mode DLL project using VS2008 but don't see one. How would you go about starting off a mixed mode DLL? – Guy Apr 08 '09 at 04:12
  • If you create a new C++ Class Library, that creates a C++ .NET DLL project. As long as the "Common Language Runtime support" setting is set to "Common Language Runtime support (/clr)", you are free to use both managed and unmanaged code in the project. – Andy Apr 08 '09 at 11:14
3

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

Kev
  • 118,037
  • 53
  • 300
  • 385
1

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.

Rob Deary
  • 977
  • 10
  • 3