How can I call to a C++ function from C#

前端 未结 1 1754
闹比i
闹比i 2020-12-02 10:55

I have C++ code. That code contains Windows mobile GPS enable/disable functionality. I want to call that method from C# code, that means when the user clicks on a button, C#

相关标签:
1条回答
  • 2020-12-02 11:10

    I'll give you an example.

    You should declare your C++ functions for export like so (assuming recent MSVC compiler):

    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;
    }
    

    And compile your C++ project as a dll library. Set your project target extension to .dll, and Configuration Type to Dynamic Library (.dll).

    enter image description here

    Then, in C# declare:

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

    Then you can call your C++ test function, as you would expect. Note that it may get a little tricky once you want to pass strings, arrays, pointers, etc. See for example this SO question.

    0 讨论(0)
提交回复
热议问题