I have an ASP.NET website that uses C# and I’d like to call functions from an unmanaged C/C++ DLL. How do I do it?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
-
create an unmanaged dll:
extern "C" __declspec(dllexport) __cdecl int sum(int a,int b); ---->
-
create a namespace/class to DllImport the above DLL
using System.Runtime.InteropServices; namespace ImportDLL { public class importdll { public importdll() { } DllImport("mysum.dll", EntryPoint="sum", ExactSpelling=false, CallingConvention = CallingConvention.Cdecl)] public extern int myfun(int a, int b); } } -
create a aspx code behind
using ImportDLL; namespace TEST { public int my_result; protected importdll imp = new importdll(); my_result = imp.myfun(1,1); }
Method 2
Check out P/Invoke.
Calling Win32 DLLs in C# with P/Invoke
If it’s a COM dll, then you can use COM Interop
Method 3
Just adding that pinvoke.net is a great wiki/resource for your Win32 needs.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0