如何从 C# 调用 C++ 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9407616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:15:12  来源:igfitidea点击:

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

c#c++windows-mobilec++-cli

提问by Piraba

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++ 代码。该代码包含 Windows 移动 GPS 启用/禁用功能。我想从 C# 代码中调用该方法,这意味着当用户单击按钮时,C# 代码应该调用 C++ 代码。

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

这是用于启用 GPS 功能的 C++ 代码:

#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 header file cppdll.h:

这是头文件cppdll.h

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

How can I call that function using C#?

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

Please, can anybody help me out with this issue?

请问有人能帮我解决这个问题吗?

采纳答案by Gleno

I'll give you an example.

我给你举个例子。

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

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

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).

并将您的 C++ 项目编译为 dll 库。将项目目标扩展名设置为 .dll,将配置类型设置为动态库 (.dll)。

enter image description here

在此处输入图片说明

Then, in C# declare:

然后,在 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);
    }
}

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 thisSO question.

然后,您可以按预期调用 C++ 测试函数。请注意,一旦您想传递字符串、数组、指针等,它可能会变得有点棘手。请参阅例如这个SO 问题。