How to access a C++ Class in a C# code? - c#

I have following problem statement.
Export a C++ class in the dll (un-managed).
Create and use an object of this class in C# code.
For the first part I have the classDLL.h as follows
``
#include <iostream>
__declspec(dllexport)
class pABC{
private:
int x;
public:
void func();
};
The respective cpp is also there. On compiling I get the dll.For thesecond part of the problem I am not getting how to proceed.
Thanks.

You can't access an unmanaged class directly from C# code. You can write a small wrapper .DLL in C++/CLI, which wraps the unmanaged class in a managed class which is visible to C#.

Convert the C++ class and DLL to be COM. If you don't have access to the unmanaged code source or can't modify, you can implement a COM wrapper class in a different DLL that consumes the original DLL and proxies the functionality of the original class through a COM class.
Define an interface in an IDL file to represent your C++ class (along with a coclass declaration). Use only basic COM types in all methods (BSTR for strings, HRESULT for return codes). Complicated structs passed as params should be refactored into their own interface.
Build your COM DLL such that it outputs a type library (tlb file).
Implement the interface (including IUnknown methods) in your C++ class. Build the COM DLL and register it.
Import the type library into your C# project. Or use the type library importer. You should now be able to instantiate your C++ class (through COM) via "new".
By the way, ATL is a great framework to get going on this quickly.

Google P/Invoke or see www.pinvoke.net

[DllImport("pABC.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern void func();

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

Importing C++ custom library functions into C#

I currently have a large C++ library that I need to incorporate into a C# project. I was successful in using DllImport to get access to some functions from my library, like this:
[DllImport("MyLib.dll")]
public static extern int SampleFunction(string param);
However, I can't seem to figure out how to make it work for functions that either have a parameter or return type that is not defined within the dll itself (i.e., the code in the dll imports it from another file), such as this example function that takes in a list:
[DllImport("MyLib.dll")]
public static extern std::vector<MyClass> MyFunction(string param);
For std library functions, I know I can get the dll and import that in, but what about other classes like MyClass in the above example? Do I need to create a managed wrapper class in C++ for each of these classes, or is there another way to do this?
std::vector<MyClass>, or indeed any unmanaged C++ class, cannot be used for interop to C#. Indeed, even if you wished to consume this function from another unmanaged C++ module you'd have to make sure that you were using the same compiler and dynamic runtime as the DLL which exported the function.
You'll need to find some other way to implement this functionality. There are lots of different ways to do that.
You could expose a p/invoke interface to the functionality. That would likely involve declaring a struct to represent the data of your class, and serializing to and from that struct.
You might consider a COM interface but it won't offer great advantages over p/invoke. You'd still need to serialize your class.
A C++/CLI wrapper would be yet another option. You'd wrap the unmanaged class with a managed C++/CLI class, and then consume that from the C#.
If you need a custom class from a native lib, you'll probably need to export a type library or use managed C++ to write a wrapper. What you're effectively trying to do is marshal a piece of memory from native to managed and now have to deal with how the data type is marshaled.
If at all possible, I would actually recommend trying to do away with the marshaling as when it works it's fine, but when it breaks, it can be rage inducing to debug.
Regardless, I'm actually not sure if anything in the STL can be marshaled. At the very least, I have never seen it done. More times, I've had to do a conversion like so: How can I marshall a vector<int> from a C++ dll to a C# application?
If you want to marshal an actual class, the standard way I've done it up until now is through a type library: Import TLB into C#
Or by linking a native lib into a managed C++ class and then referencing the managed C++ dll into the C# project as a shim.
Beyond that, if you can convert the class to strict C-style functions and pass a struct around, that could allow you to just use pinvoke, this is no different from simply exporting a bunch of helper functions except you can marshal a struct representation back and forth: Marshal C++ struct array into C#

Implement C# interface in an unmanaged cpp dll

I have a C# apllication having add-ons capability. An add-on/plug-in that implements a specific interface can be linked/loaded at runtime to the main C# application.
Now to my question: how can I develop an unmanaged cpp dll that implements the C# interface and be loaded runtime to the C# app?
Thanks,
Cabbi
You can implement interface using p/inkove, for example:
public interface IDirectory
{
bool IsDirectoryEmplty(string path);
}
public class Directory : IDirectory
{
[DllImport("Shlwapi.dll", EntryPoint = "PathIsDirectoryEmpty")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsDirectoryEmplty([MarshalAs(UnmanagedType.LPStr)]string directory);
bool IInterface.IsDirectoryEmplty(string path)
{
return IsDirectoryEmplty(path);
}
}
With common language support on, you can write managed dll with full native c++ capability mixed in.
And you can load unmanaged dll via PInvoke in .Net, but I'd rather not recommend that way.
Strictly speaking, you cannot have an unmanaged DLL that implements a C# (managed) interface.
However, you can create a mixed mode assembly, that might be what you want. This is a very common way to provide a native C++ (unmanaged) implementation with a .NET wrapper making it an assembly that looks managed to a C# (or other .NET language) consumer.
In addition, you can use PInvoke to consume a pure native DLL from a NET assembly.

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");

Instantiating a C++ class in C# using P/Invoke via a pointer

I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to generate a PE file. This function returns a pointer to an C++ object defined here, is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?
The code I'm using currently is as follows:-
[DllImport(#"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);
N.B.: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.
You need a wrapper library to be able to use the class from C#.
The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class. This will eliminate the need to use P/Invoke for anything.
(Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).
It looks like COM class/interface. Can you not just use COM instead?

Categories

Resources