程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#中如何調用C生成DLL文件

C#中如何調用C生成DLL文件

編輯:關於C#

環境: VS2010, Win7

1. 添加新項目->Win32項目 輸入名稱:CSInvokeCDll

2.應用程序設置中選擇DLL然後點擊完成

3 在CSharpInvokeCPP.CPP中書寫C代碼

#include "stdafx.h"     
#include "malloc.h"     
#include "userinfo.h"     
         
typedef struct {     
    char name[32];     
    int age;     
} User;      
         
UserInfo* userInfo;     
         
extern "C" __declspec(dllexport) int Add(int x, int y)      
{      
    return x + y;      
}     
         
extern "C" __declspec(dllexport) int Sub(int x, int y)      
{      
    return x - y;      
}     
         
extern "C" __declspec(dllexport) int Multiply(int x, int y)      
{      
    return x * y;      
}     
         
extern "C" __declspec(dllexport) int Divide(int x, int y)      
{      
    return x / y;      
}     
         
extern "C" __declspec(dllexport) int Sum(int * parr, int length)     
{     
    int sum = 0;     
    if(parr == NULL)     
        return sum;     
         
    for(int i = 0; i < length; i++)     
    {     
        sum += *parr++;     
    }     
         
    return sum;     
}     
         
extern "C" __declspec(dllexport) User* Create(char* name, int age)         
{        
    User* user = (User*)malloc(sizeof(User))     
    strcpy(user->name, name);     
    user->age = age;     
         
    return user;      
}

4 添加C#控制台應用程序, 並命名為CSInvokeCPP

5 創建C#對CPP 生成Dll的引用類CPPAdapter

public class CPPAdapter     
    {     
        [DllImport("CSharpInvokeCPP.CPPDemo.dll")]     
        public static extern int Add(int x, int y);     
         
        [DllImport("CSharpInvokeCPP.CPPDemo.dll")]     
        public static extern int Sub(int x, int y);     
         
        [DllImport("CSharpInvokeCPP.CPPDemo.dll")]     
        public static extern int Multiply(int x, int y);     
         
        [DllImport("CSharpInvokeCPP.CPPDemo.dll")]     
        public static extern int Divide(int x, int y);     
         
        [DllImport("CSharpInvokeCPP.CPPDemo.dll")]     
        public static extern int Sum(int[] Parr , int length);     
         
        [DllImport("CSharpInvokeCPP.CPPDemo.dll")]     
        public static extern IntPtr Create(string name, int age);     
         
        [StructLayout(LayoutKind.Sequential)]     
        public struct User     
        {     
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]     
            public string Name;     
         
            public int Age;     
        }     
         
                
    }

6 把CSInvokeCDll.dll復制到CSInvokeCPP下的/bin/Debug目錄下

查看本欄目

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved