P/Invoke C++ Class in C# - c#

I want to use rasterbar libtorrent in a C# application. It's written in unmanaged C++.
I'm new at using DLLs and found this article online: How to Marshal a C++ Class
It describes that it's not possible to marshal/invoke a C++ class directly and you have to write a bridge in C (or managed C++) in order to use the library in managed C# code.
The article is from 2007 and I wonder if there is a better solution to use C++ DLLs by now. I'm looking for solutions that also work on the Mono platform. libtorrent is cross plattform so it should be possible.

First you should have the libtorrent dll built for windows. This link here can help you. Then for calling the un-managed code (C++ in this case) from the managed code (C# in this case) you can use Platform Invocation Services (PInvoke). It allows managed code to call unmanaged functions that are implemented in a DLL. For example have a look on this MSDN code
// PInvokeTest.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts(string c);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Main()
{
puts("Test");
_flushall();
}
}
The better approach will be to write a wrapper class in C# for libtorrent dll, wrap it's methods using PInvoke and use the wrapper throughout your project.

Related

How to ger method of class from a loaded C# dl-library in C++? [duplicate]

How to call managed c# functions from unmanaged c++
Or use a project of mine that allows C# to create unmanaged exports. Those can be consumed as if they were written in a native language.
I used COM interop first, but by now I switched to IJW (it just works), as it is a lot simpler. I have a wrapper C++/CLR DLL (compile with /clr).
A simple example (using statics to make the calls easier):
namespace MyClasses
{
public class MyClass
{
public static void DoSomething()
{
MessageBox.Show("Hello World");
}
}
}
In the DLL I can reference namespaces as follows:
using namespace MyClasses;
And call it:
__declspec(dllexport) void CallManagedCode()
{
MyClass::DoSomething();
}
Now you have an unmanaged DLL export "CallManagedCode" which calls into the managed code.
Of course, you also have to convert data between the managed/unmanaged boundary. Starting with VS2008, Microsoft includes a marshal-helper for converting between unmanaged and managed types. See http://msdn.microsoft.com/en-us/library/bb384865.aspx
I used C++/CLI wrapper classes described here and it was relatively easy to implement.
RE: How to call managed C# code from an unmanaged C++ application?
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.interop/2005-05/msg00030.html
Calling Managed .NET C# COM Objects from Unmanaged C++ Code ...
http://www.codeproject.com/KB/cs/ManagedCOM.aspx
Wrapping a managed C# DLL in a unmanaged C++ project : dll .
http://www.experts-exchange.com/Programming/Languages/.NET/Q_22006727.html

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.
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.
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.
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.

Accessing a C++ .lib library from c#

I have a c++ library file (.lib). How can I access the functions within it from C#? I have read that I could wrap the library file in a c++ dll and expose the functions that way. Is that the only way? I am not the owner of the code, so my options are limited.
Wrap the C++ lib with a C++/CLI assembly.
C++/CLI allows you to mix managed and unmanaged code, serving as a bridge between C# and native C++. It's actually very straightforward and relatively easy to do, although it can get tedious if you have a lot of classes/functions to wrap.
Here is one example.
You can not access a c++ library file (.lib) directly. The best way is to have an unmanaged wrapper around your unmanaged code. Reference DllImportAttribute.
There's a good example of it's usage in the MSDN help document:
using System;
using System.Runtime.InteropServices;
class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}
Also note: You can have a managed c++ wrapper around your c++ library, but it's better to write your wrapper in unmanaged c++ code.

Building C# Wrapper around C++ lib files

I have couple of lib files and I want to use in my project. How to build the C# Wrapper around C++ lib files.
Any weblink or any tutorial you know, please send me.
Thanks in advance.
Harsha
Create a C++ CLR Class Library project, and then write a C++/CLI class which wraps the functions in your libs.
From C#, you can then add a reference to your class library, and call the class and its methods directly.
After creating the C++ CLR class library.
You can also consume it using DLLImport
//c# code
[DllImport(#CPPProjectName, CallingConvention = CallingConvention.StdCall)]
public static extern void SendData(string args);
Invoke the method in normal way
SendData("data123");

How to export C# methods?

How can we export C# methods?
I have a dll and I want to use its methods in the Python language with the ctypes module.
Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python.
So, how can I export the C# methods (like they do in C++)?
Contrary to popular belief, this is possible.
See here.
With the normal Python implementation ("CPython"), you can't, at least not directly.
You could write native C wrappers around our C# methods using C++/CLI, and call these wrappers from Python.
Or, you could try IronPython. This lets you run Python code and call code in any .Net language, including C#.
That's not possible. If you need DLL exports you'll need to use the C++/CLI language. For example:
public ref class Class1 {
public:
static int add(int a, int b) {
return a + b;
}
};
extern "C" __declspec(dllexport)
int add(int a, int b) {
return Class1::add(a, b);
}
The class can be written in C# as well. The C++/CLI compiler emits a special thunk for the export that ensures that the CLR is loaded and execution switches to managed mode. This is not exactly fast.
Writing [ComVisible(true)] code in C# is another possibility.
(This may no longer be relevant since SLaks has found that ingenious link, but I'll leave an edited version for reference...)
The "normal" way of exposing .NET/C# objects to unmanaged code (like Python) is to create a COM-callable wrapper for the C# DLL (.NET assembly), and call that using Python's COM/OLE support. To create the COM-callable wrapper, use the tlbexp and/or regasm command-line utilities.
Obviously, however, this does not provide the C/DLL-style API that SLaks' link does.

Categories

Resources