如何调用从C#C ++ code [英] How to call C++ code from C#

查看:197
本文介绍了如何调用从C#C ++ code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C ++ code。这code包含Windows移动GPS启用/禁用功能。我想,当用户点击一个按钮来调用从C#code的方法,这意味着,C#code要调用C ++ code。

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# code should call into C++ code.

这是C ++ code启用GPS功能:

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

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

这是头文件 cppdll.h

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

我如何调用该函数使用C#?

How can I call that function using C#?

请,任何人可以帮助我走出这个问题?

Please, can anybody help me out with this issue?

推荐答案

我给你举个例子。

您应声明你的C ++函数用于出口,像这样(假设最近MSVC编译器):

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

和编译C ++项目作为dll库。设置项目的目标扩展.dll和配置类型为动态库文件(.dll)。

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

然后,在C#中申明:

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

然后你可以打电话给你的C ++测试功能,如你所愿。请注意,它可能会变得有点棘手,一旦你想传递一个字符串,数组,指针等,例如,见<一href=\"http://stackoverflow.com/questions/741206/using-arrays-and-pointers-in-c-sharp-with-c-dll\">this SO问题。

这篇关于如何调用从C#C ++ code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆