Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call unmanaged C/C++ code from a C# ASP.NET webpage

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?

like image 597
Mendokusai Avatar asked Apr 06 '09 01:04

Mendokusai


People also ask

How is unmanaged code executed?

Execution of Unmanaged Code In C# the unmanaged code is directly executed by the operating system. Generally, the executable files of unmanaged or unsafe code are in the form of binary images which are loaded into the memory.

Can you call C# code from C++?

C++/CLI can call any C# function as if it were a "regular" C++ function. Add your references, /clr and It Just Works.


2 Answers

  1. create an unmanaged dll:

    extern "C" __declspec(dllexport) __cdecl int sum(int a,int b); ---->
    
  2. 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);
    }
    }
    
  3. create a aspx code behind

    using ImportDLL;
    namespace TEST
    {
     public int my_result;
     protected importdll imp = new importdll();
     my_result = imp.myfun(1,1);
    }
    
like image 96
Vinay Avatar answered Sep 18 '22 23:09

Vinay


Check out P/Invoke.

Calling Win32 DLLs in C# with P/Invoke

If it's a COM dll, then you can use COM Interop

like image 38
J.W. Avatar answered Sep 19 '22 23:09

J.W.