Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 873
Guy Avatar asked Apr 08 '09 02:04

Guy


People also ask

Can you call in C?

Function Calling: A function call is an important part of the C programming language. It is called inside a program whenever it is required to call a function. It is only called by its name in the main() function of a program. We can pass the parameters to a function calling in the main() function.

Can I call C from rust?

Rust can link to/call C functions via its FFI, but not C++ functions. While I don't know why you can't call C++ functions, it is probably because C++ functions are complicated. You can just define C linkage on any C++ function, making it available from C and thus also Rust. extern "C" is your friend here.

Can you call C from C++?

Just declare the C function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code. extern "C" void f(int); // one way.

Can I convert C++ to C?

It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.


2 Answers

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.

like image 69
Andy Avatar answered Oct 05 '22 22:10

Andy


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

like image 23
Kev Avatar answered Oct 06 '22 00:10

Kev