[英]How to write my C++ function so I can call it from C#?
我有 C++ 代碼。 該代碼包含 Windows 移動 GPS 啟用/禁用功能。 我想從 C# 代碼中調用該方法,這意味着當用戶單擊按鈕時,C# 代碼應該調用 C++ 代碼。
這是用於啟用 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);
}
這是頭文件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++ 測試函數。 請注意,一旦您想傳遞字符串、數組、指針等,它可能會變得有點棘手。請參閱例如這個SO 問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.