vs2010+win7经测试,可以正常调用。疑惑rt,如果存在问题,该如何解决?谢谢。using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;namespace WindowsFormsApplication3//测试程序
{
   
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
         int ret= mycl.test(testarr.arr);
            for (int k = 0; k < testarr.arr.Length; ++k)
            {
                textBox1.Text = textBox1.Text + testarr.arr[k].ToString();
            }
          public class mycl
           {
            [DllImport("testdll.dll")]
             public static extern int test(int[] arr);
//testdll为c++写的win32 dll,里面有个test函数,对传入的数组进行初始化
           }         public class testarr 
        {
           public unsafe static int[] arr = new int[100];
         }
       
      
}

解决方案 »

  1.   

    testdll的test没有内存问题就 没问题.
      

  2.   

    上面的代码虽然带unsafe关键字,但其实根本不包含不安全代码
    arr 只是正常的托管数组。关键字new无法分配非托管内存。不安全的固定大小缓冲区的定义类似于:
    unsafe struct testarr
    {
    public fixed int arr[32];  //请留意括号'[]'的位置
    }
    如果楼主只是要调用dll,毋须使用不安全代码。把unsafe去掉,它是多余的,Interop会进行默认封送处理,自动在托管内存和非托管内存之间进行所需的数据处理或复制。如果要求数组返回数据,则:
    public static extern int test([In, Out] int[] arr);