Calling C++ Native (Unmanaged) code from (Managed) C# code:
C# can call C++ code only if C++ code is a DLL (Dynamic Link Library).
Create a C++ project in Visual Studio and change its type to a DLL.
Here is what you would do:
A reference to dll could not be added. Please make sure that the file is accessible and that it is a valid assembly or COM component. You are not done yet, you have to write C++ code in a different way.
You need to code in a format similar to the following:
extern "C" { __declspec(dllexport) int TestFunc() { } __declspec(dllexport) int TestFunc1() { } }
In the above code:
extern "C" //write exactly like this, can contain multiple functions __declspec(dllexport) //Tells to export this function int //return type of the function __cdecl //Specifies calling convention,cdelc is default, so this can be omitted // and function TestFunc() { }
Write some functions and Build it. And grab the DLL created.
Now on the C# part,
you don’t have to reference that DLL into a C# project,
you need to put the DLL somewhere and copy the full path of it.
You cannot use Add Reference to easily import this DLL to C# project.
If you try, you may get the error saying:
A reference to dll could not be added. Please make sure that the file is accessible and that it is a valid assembly or COM component.
In the C# code, you have to redefine each function you need to call.
[DllImport("dllpath.dll", CallingConvention=CallingConvention.Cdecl)] extern void TestFunc1(); [DllImport("dllpath.dll", CallingConvention=CallingConvention.Cdecl)] extern void TestFunc1();
Following is the full specification of DllImport:
[DllImport("SomeDll.dll", EntryPoint = "TestFunc", SetLastError = true, Charset = Charset.Ansi, ExactSpelling = true, CallingConvention=CallingConvention.Cdecl)]
DLL path is compulsory to specify, all others are optional i.e., if not specified, default values will be used.
Each function needs to be redefined that the following DLL contains this function, with specified EntryPoint and specified CallingConvention.
If all went well, when you call these methods from C#, it will call the methods of C++ code from the DLL.
If something went wrong, you may get an EntryPointNotFoundException, and you might need to re-check the whole procedure again.