How to call C ++ code from C #

I have C ++ code. This code contains GPS enable / disable features for Windows mobile devices. I want to call this method from C # code, that is, when a user clicks a button, C # code must call C ++ code.

This is the C ++ code for enabling GPS functions:

#include "cppdll.h" void Adder::add() { // TODO: Add your control notification handler code here HANDLE hDrv = CreateFile(TEXT("FNC1:"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (0 == DeviceIoControl(hDrv, IOCTL_WID_GPS_ON, NULL, 0, NULL, 0, NULL, NULL)) { RETAILMSG(1, (L"IOCTL_WID_RFID_ON Failed !! \r\n")); return; } CloseHandle(hDrv); return (x+y); } 

And this is the cppdll.h header file:

  class __declspec(dllexport) Adder { public: Adder(){;}; ~Adder(){;}; void add(); }; 

How can I call this function using C #?

Please can someone help me with this problem?

+8
c ++ c # windows-mobile c ++ - cli
source share
1 answer

I will give you an example.

You must declare your C ++ functions for export as follows (assuming the latest 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. Install the target project extension in .dll and the type of configuration in a 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. Please note that if you want to pass strings, arrays, pointers, etc., this can be a little complicated. See for example this SO question.

+17
source share

All Articles