C++ 調用c#DLL函數

自己實踐了一下,其實不是很難,怕自己忘記掉,再加上有幾個需要注意的問題,這裏記錄下來。

1. c# 創建dll  library

 

using System;
using System.Collections.Generic;
using System.Text;

namespace AddDll
{
    public class Add
    {
        public int iadd(int a, int b)
        {
            int c = a + b;
            return c;
        }
    }
}


2. c++實現調用程序

這裏創建一個Win32的控制檯應用程序

Configure:右鍵點擊解決方案資源管理器中的UseDll,選擇“屬性”,將公共語言運行庫支持設置爲“公共語言運行庫支持(/clr)” 即Common Language Runtime Support (/clr)

PS:如果你是建立一個MFC程序的話,必須把Use of MFC設置成:Use MFC in a Shared DLL 共享dll,不然會引起衝突

(error D8016: '/clr' and '/MTd' command-line options are incompatible 錯誤)

#include "stdio.h"

#using "..\debug\AddDll.dll"
using namespace AddDll;

int main(){
        int result;
        Add ^add = gcnew Add();   //生成託管類型
//gcnew creates an instance of a managed type (reference or value type) on the garbage //collected heap. The result of the evaluation of a gcnew expression is a handle (^) to //the type being created.        result = add->iadd(10,90);
        printf("%d",result);
        scanf("%s");
        return 0;
}

 

Attention:

1. 使用#using引用dll,而不是#inculde。

2. 別忘了using namespace CSLib

3. 使用C++/clr語法,採用正確的訪問託管對象,即:使用帽子‘^’,而不是星星‘*’。

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