C#調用C/C++寫的dll

C++ 代碼:

頭文件:

extern "C" _declspec(dllexport)bool openWindow(char*classname,char*name);

EXTERN_C _declspec(dllexport)bool openWindow(char*classname,char*name);

extern "C"{
    _declspec(dllexport)bool openWindow(char*classname,char*name);
}
EXTERN_C{
_declspec(dllexport)bool openWindow(char*classname,char*name);
}

cpp中:
和普通方法一樣

bool openWindow(char*classname, char*name)
{
    hwnd = FindWindowA(classname,name);
    if (hwnd == 0)return false;
    tid=GetWindowThreadProcessId(hwnd, &pid);
    handle = OpenProcess(PROCESS_ALL_ACCESS,false,pid);
    if (handle == 0)return false;
    return true;
}

C#代碼

[DllImport(@"C:\Users\Liziguo\source\repos\C Sharp\Debug\waigua.dll",
EntryPoint = "openWindow", 
CallingConvention = CallingConvention.Cdecl)]

extern static bool openWindow(string classname,string name);

第一個參數 dll路徑
第二個參數 指定函數名,如果C#中的函數名和C++中的函數名一樣的話可以不填
第三個參數 解決:對 PInvoke 函數的調用導致堆棧不對稱問題,照着填就好

如果是C#引用C#編寫的dll直接在項目那右鍵添加引用就可以了,記得導入命名空間

若有不正之處,請多多諒解並歡迎指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章