环境: 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目录下
7 main函数调用:
static void Main(string[] args)
{
int result = CPPAdapter.Add(10, 20);
int[] arr = new int[] { 1, 2, 3, 4, 5 };
Console.WriteLine("10 + 20 = {0}", result);
result = CPPAdapter.Sub(30, 12);
Console.WriteLine("30 - 12 = {0}", result);
result = CPPAdapter.Multiply(5, 4);
Console.WriteLine("5 * 4 = {0}", result);
result = CPPAdapter.Divide(30, 5);
Console.WriteLine("30 / 5 = {0}", result);
result = CPPAdapter.Sum(arr, 5);
Console.WriteLine("sum is {0}", result);
IntPtr ptr = CPPAdapter.Create("Chevkio", 27);
CPPAdapter.User user = (CPPAdapter.User)Marshal.PtrToStructure(ptr, typeof(CPPAdapter.User));
Console.WriteLine("Name: {0}, Age: {1}", user.Name, user.Age);
Console.ReadLine();
}
调用结果:
总结:
本文实现了C#通过DllImport和Marshal类对C Dll文件的引用 对于native C++, CLI/C++ 及 C#的效率问题会在下面文章中提到.
疑问:
在C函数Create中申请了内存空间
User* user = (User*)malloc(sizeof(User));
不知道在哪里释放比较合适. 请高手指点