C#调用C++Dll

1,本人闲着的使用做的一个测试,原因:上家公司Unity3D使用C++封装的Socket用C#来调用.这是一个例子,事实上,如果一些运算量大的功能用C++来写,然后使用C#调用的话,一来可以优化性能(你懂的),而来可以隐藏(保护)代码.不多说了,上测试

C++代码:

// CSharpMInvoke.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"


extern "C" __declspec(dllexport) int Add( int x , int y ){
	return x + y;
}

wKiom1acxP6wqoTxAAIwrhicYoM241.png

wKiom1acxP-TJHLuAAFxu04arQU283.png

wKioL1acxTnS6W7gAAEyCvkGqiw760.png

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpDll
{
    public class CPPDll
    {
        [System.Runtime.InteropServices.DllImport("CSharpMInvoke.dll",  CallingConvention=System.Runtime.InteropServices.CallingConvention.Cdecl)]
        public static extern int Add(int x, int y);
    }
}

注意:将C++生成的dll文件(Bin文件夹中)复制到C#项目Bin/Debug中

这里是:CSharpMInvoke.dll

源文件:

wKiom1acvTuTLETyAABjhYlblvs108.png

你可能感兴趣的:(C#,dllimport)