Alaa M.
Alaa M.

Reputation: 5273

using a c++ function in c#

i have a function defined in c++, and i want to include it in some c# gui. This is what i've done:

in cpp file:

extern "C"             //No name mangling
__declspec(dllexport)  //Tells the compiler to export the function
int                    //Function return type     
__cdecl                //Specifies calling convention, cdelc is default, 
                   //so this can be omitted 
test(int number){
    return number + 1;
}

in cs file:

...
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = test(9);
        }
    }

    public static class NativeTest
    {
        private const string DllFilePath = @"c:\test.dll";
        [DllImport(DllFilePath , CallingConvention = CallingConvention.Cdecl)]
        static extern int test(int a);

    }
}

and i get this error:

Error 1 The name 'test' does not exist in the current context Line 28

Any help is appreciated

Thanks

Upvotes: 0

Views: 189

Answers (1)

RichieHindle
RichieHindle

Reputation: 281485

You need to call NativeTest.test() rather than just test().

Upvotes: 4

Related Questions