Use c++ libraries at C# - c#

I'm working myself on a project, because performance is important i want to write some part of the code on c++ and want to call c++ codes from C#. I will write c++ library and want to write a C# wrapper, how can i do it? Have you any suggestion where i should begin to study? [any website, any link, any book]
Thanks !

Example:
Windows:
[DllImport("User32.dll")]
public static extern void SetWindowText(int h, String s);
Linux:
[System.Runtime.InteropServices.DllImport("/root/Desktop/q3noclient/libnoclient.so")]
static extern int DisconnectClient (string strServerIP, int iServerPort, string strClientIP, int iClientPort);
C#:
[DllImport("Comdlg32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern bool GetSaveFileName(ref OPENFILENAME lpofn);
VB.NET:
<DllImport("Comdlg32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function GetSaveFileName(ByRef lpofn As OPENFILENAME) As Boolean
End Function

You need to either make C style imports for P/Invoke to use, like
void World_Hello(World* self) { self->Hello(); }
or investigate CallingConvention.ThisCall. Thanks to name mangling, if you want to be portable to other OSes the former is a better choice.

Take a look at C++/CLI. I would recommend C++/CLI in Action by Nishant Sivakumar. Also, check this link out: http://msdn.microsoft.com/en-us/magazine/cc163855.aspx#S7

Related

Problems using methods from DLL - EntryPoints

I need to use a DLL created in C in a C # application. I have followed several ways seen on the internet and I can not use the methods that are supposed to be in the DLL.
When looking for the entrypoints I get 4, which are the following.
DllCanUnloadNow
llGetClassObject
DllRegisterServer
DllUnregisterServer
I'm trying with the following code:
[DllImport("DLL.dll", EntryPoint ="DllCanUnloadNow" ,CharSet = CharSet.Auto)]
public static extern int Open();
static void Main(string[] args)
{
Console.WriteLine(Open());
Console.ReadLine();
}
It doesn't matter what function I use, it returns always 0.
If I use a function called for example, asdf() I got 0.
Does anyone know how to use the DLL correctly? I think it's made as COM and I have a .lib file.
Thanks in advance.

how to pass window handle to c++ win32 dll from C#

I have one project which capture images from multiple cameras which is in C++ .I want to use that project in my new project which is in C#.I had made dll of that project.My question is ,how can i use that dll in my project.I know by passing window handle to C++ dll we can use it but i dont know how to do it and what changes should i make in dll.
Please forgive ,if it is foolish question.
I had the exact problem as you and this article helped me.
http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-_2800_c_23002900_.aspx
To pass the handle, you can add another function in C++ end. Something like,
(in the header)
extern "C" __declspec(dllexport) void SetParent(HWND hWnd);
To use the SetParent in C#
class Program
{
...
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SetParent(IntPtr hWnd);
public void testMethod()
{
...
IntPtr getAddress = NativeMethods.GetProcAddress(pDll, "SetParent");
...
SetParent setParent = (SetParent)Marshal.GetDelegateForFunctionPointer(getAddress, typeof(SetParent));
setParent(this.Handle);
...
}
}
If your C++ project is already in a DLL you can call any functions that it exports using P/Invoke. You will have to declare the method in your C# assembly as shown below, but then you can call it like a standard static method.
[DllImport("YourDllsName.dll")]
public static extern bool FunctionThatAWindowHandleAndReturnsBool(IntPtr hWnd);
Depending on the types of parameters that your C++ DLL's functions take the marshaling of the .Net datatypes to C data types can get complicated.

Windows kernel32 functions in Mono on Linux

I got this awesomely simple ini class that I downloaded from somewhere a while ago, but now that I'm using mono I'm running into the issue that it's importing stuff from kernel32
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
Which on mono (in linux) gives the error DLLNotFoundException: kernel32
Is there any way to get this to work with mono? Maybe embed the whole thing into the assembly at compile time (if that even makes sense at all, I wouldn't know). Or will I have to create/find an ini class that doesn't use WinAPI? (Nini springs to mind).
I'd really like it if WinAPI stuff could work with Mono, any thoughts?
Mono supports C#'s P/Invoke, which is what's required for running Win32 API functions. (As long as you're running Mono on Windows--the fact that it can't find "kernel32" causes me to suspect you're not.)
The site pinvoke.net collects the necessary DllImport signatures for most of the Win32 API.
Here's what it has to say about GetPrivateProfileString.
This code worked for me using Mono 2.10.8 on Windows 7:
using System;
using System.Text;
public class MainClass
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
static void Main()
{
StringBuilder asdf = new StringBuilder();
GetPrivateProfileString("global","test","",asdf,100,#"c:\example\test.ini");
Console.WriteLine(asdf.ToString());
}
}
You'll need to rewrite the functionality of those functions in native .NET to use them on Mono/Linux (unless you can convince Mono and Wine to play nicely).
If the INI files are controlled, then you may get away with simple file/string manipulation, but then you may be better off moving to something a bit more cross platform anyway.
Change [DllImport("kernel32")] into [DllImport("kernel32.dll")]
Everything will start working like supposed to.

How to hack Win32 API to get character limit to 32K

I want to use prefix \\\?\ as stated in this msdn BCL Team Blog, Long Paths in .NET, Part 2 of 3: Long Path Workarounds [Kim Hamilton]
Even after going through it again and again, I couldn't figure out how to actually use this feature, wondering if anyone can tell me simplest way to use it and how.
Note: I want to use it for creating a directory
You have to use Win32 functions and P/Invoke to achieve this. Use the Unicode version of the API.
Here's what you're looking for:
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes);
public static void CreateDir(string dirPath)
{
if (!CreateDirectory(#"\\?\" + dirPath, IntPtr.Zero))
{
throw new IOException("Could not create dir");
}
}
CreateDirectory method
More information about how naming works in Windows

Referencing unmanaged librararies from managed code, adventages and disadvantages?

HI all,
I would like to call from my C# code, unamanaged library functions like presented below. There are two options and the both works. In this moment "Beep" function is simple and have no input/output parameters, pointers, references... I am wondering in more complex cases what would be adventages and disadvantage of both approches ?
Thanks,
Milan.
[DllImport("kernel32.dll")]
public static extern bool Beep(uint iFreq, uint iDuration);
public void TestBeep()
{
Beep(300, 3000);
}
internal delegate bool DelegBeep(uint iFreq, uint iDuration);
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String procName);
public void BeepIt()
{
IntPtr kernel32 = LoadLibrary("Kernel32.dll");
IntPtr procBeep = GetProcAddress(kernel32, "Beep");
DelegBeep delegBeep = Marshal.GetDelegateForFunctionPointer(procBeep, typeof(DelegBeep)) as DelegBeep;
delegBeep(50, 1000);//Hz,ms
}
Your second one is much more complicated than the first but achieves the same thing in this case.
If the name of the DLL and the name of the function are known at compile time, then stick with the first approach. If you don't know the name of the DLL and/or function until run time then the LoadLibary/GetProcAddress approach is your only option.
The P/Invoke marshaller finds an entrypoint in a DLL by using LoadLibrary() and GetProcAddress(). And knows how to convert a C# declaration to the equivalent of a delegate declaration.
Doing this yourself has no advantage beyond maybe a wee bit of efficiency. Which you'd better measure, it is no slamdunk.

Categories