如何从C#调用C ++代码
我有C ++代码。 该代码包含Windows移动GPS启用/禁用function。 我想从C#代码调用该方法,这意味着当用户单击按钮时,C#代码应调用C ++代码。
这是用于启用GPSfunction的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); }
这是头文件cppdll.h
:
class __declspec(dllexport) Adder { public: Adder(){;}; ~Adder(){;}; void add(); };
如何使用C#调用该函数?
请问,任何人都可以帮我解决这个问题吗?
我给你举个例子。
您应该声明您的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; }
并将您的C ++项目编译为DLL库。 将项目目标扩展名设置为.dll,将“配置类型”设置为“动态库”(.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 ++测试函数。 请注意,一旦你想传递字符串,数组,指针等,它可能会有点棘手。例如,参见这个问题。
- WebApi.Owin中的SuppressDefaultHostAuthentication还禁止webapi之外的身份validation
- 如何在运行时修改PropertyGrid(添加/删除属性和动态类型/枚举)
- 将C#字符串传递给C ++并将C ++结果(字符串,字符*等)传递给C#
- 如何突出显示DataGridView行或使其暂时发光?
- entity framework – 对唯一索引的UPSERT
- HttpClient请求像浏览器
- 如何使textBox仅接受数字,只接受Windows 8中的一个小数点
- 在asp.net 3.5中使用RegisterClientScriptBlock / RegisterStartupScript
- 在C ++中部署GBM模型| 让Predict.gbm在R之外工作
- 将Platform :: String转换为std :: string
- 修复了google-code-prettify w / c#