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;
}



struct MyData
{
    int data[10];
};

extern "C" __declspec(dllexport) void GetData(MyData * pData)
{
    pData->data[0] = 1;
    pData->data[1] = 2;
    pData->data[2] = 3;
   
}


2 编译生成dll

3 新建一个C#控制台项目

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

namespace ConsoleApp
{

    struct MyData
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
        public int[] data;
    };
 
    class Program
    {
        [DllImport("DLL.dll", EntryPoint = "GetData", CallingConvention = CallingConvention.Cdecl)]
        private extern static void GetData(ref MyData pData);//用ref声明结构
        static void Main(string[] args)
        {

            MyData sd = new MyData();
            sd.data = new int[10];            
            GetData(ref sd);
        

            Console.Read();


        }
    }
}

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