環境: 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目錄下
查看本欄目