C#调用C++ dll中的函数

1 新建C++ dll项目,添加方法 

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}


extern "C" __declspec(dllexport) int Avg(int* buf, int count)
{
    int sum = 0;
    for (size_t i = 0; i < count; i++)
    {
        sum += buf[i];
    }
    return sum / count;
}

2 新建C#控制台项目,将上面生成的dll拷贝到项目的Debug文件夹,修改代码 

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

namespace TestPointerDLL
{
    class Program
    {
        [DllImport("PointerDLL.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
        extern static int Avg(int[] buf, int count);
        static void Main(string[] args)
        {
            int[] data = { 1, 2, 3, 4, 5 };

            int res = Avg(data, 5);

        }
    }
}

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