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

倾然丶 夕夏残阳落幕 提交于 2019-11-27 07:31:06

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!