Tutorial by Examples

Here is an example of how to import a function that is defined in an unmanaged C++ DLL. In the C++ source code for "myDLL.dll", the function add is defined: extern "C" __declspec(dllexport) int __stdcall add(int a, int b) { return a + b; } Then it can be included into ...
using System; using System.Runtime.InteropServices; namespace ComLibrary { [ComVisible(true)] public interface IMainType { int GetInt(); void StartTime(); int StopTime(); } [ComVisible(true)] [ClassInterface(ClassInterfaceType.N...
C++ compilers encode additional information in the names of exported functions, such as argument types, to make overloads with different arguments possible. This process is called name mangling. This causes problems with importing functions in C# (and interop with other languages in general), as the...
There're several conventions of calling functions, specifying who (caller or callee) pops arguments from the stack, how arguments are passed and in what order. C++ uses Cdecl calling convention by default, but C# expects StdCall, which is usually used by Windows API. You need to change one or the ot...
When using the DllImport attribute you have to know the correct dll and method name at compile time. If you want to be more flexible and decide at runtime which dll and methods to load, you can use the Windows API methods LoadLibrary(), GetProcAddress() and FreeLibrary(). This can be helpful if the ...
When using interop methods, you can use GetLastError API to get additional information on you API calls. DllImport Attribute SetLastError Attribute SetLastError=true Indicates that the callee will call SetLastError (Win32 API function). SetLastError=false Indicates that the callee will not call...
GC (Garbage Collector) is responsible for cleaning our garbage. While GC cleans our garbage, he removes the unused objects from the managed heap which cause heap fragmentation. When GC is done with the removal, it performs a heap compression (defragmintation) which involves moving objects on the he...
Marshal class contains a function named PtrToStructure, this function gives us the ability of reading structures by an unmanaged pointer. PtrToStructure function got many overloads, but they all have the same intention. Generic PtrToStructure: public static T PtrToStructure<T>(IntPtr ptr); ...

Page 1 of 1