Tuesday, November 25, 2025

c++ - How to make .dll and call it from c#

c++ DLL cpp:
extern "C" __declspec( dllexport )
int math_add( int const d1, int const d2 ) {
    return d1 + d2;
}
Test c++ console app:
#include 

extern "C" __declspec( dllimport ) int math_add( int, int );

int main( int argc, char* argv[] )
{
    int i = math_add( 4, 5 );

    std::cout << '\n' << i << '\n';
    
    std::cout << "Press any key..";

    std::cin.get();

    return 0;
}
C# class:
using System.Runtime.InteropServices;

namespace test {
    public class PILib {

        [DllImport( "piMath.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int math_add( int _v1, int _v2);

    }
}
Calling in c#:
private void button1_Click( object sender, EventArgs e ) {
    int i = PILib.math_add( 3, 5 );

    MessageBox.Show( i.ToString() );
}
Output:

No comments:

Post a Comment