如何从C#调用C ++函数 [英] How can I call to a C++ function from C#
问题描述
我有C ++代码。该代码包含Windows移动GPS启用/禁用功能。我想从C#代码中调用该方法,这意味着当用户单击按钮时,C#代码应调用C ++代码。
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 ++代码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 ++测试函数会期望的。请注意,一旦您要传递字符串,数组,指针等,它可能会变得有些棘手。例如,请参见这个 SO问题。
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.
这篇关于如何从C#调用C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!