高手们好,我才用C#不久,用到一个C++编写的动态库,在动态库的接口中含有结构类型的参数。
对于由简单数据类型构成的结构类型参数,我已经调用成功了,但有的结构参数里面含有数组,使用的时候报出不支持异常。
比如一个简单的代码如下:
C++代码:
struct stru1   //结构类型
{
   int x;
   int y;
   int xx[2];
}int add(stru1 stru)       //动态库中函数,已在其函数声明中作为外部接口
{
   return x+y+xx[0]++xx[1];
}C#中代码:
...
public struct stru1
{
   public int x;
   pubilc int y;
   public int[] xx;
}
...
[DllImport("TestDll.dll")]
unsafe public static extern int add(stru1 stru);
...
/* 调用动态库 */
stru1 stru;
stru.xx = new int[2];
stru.x = 2;
stru. y = 3;
stru.xx[0] = 10;
stru.xx[1] = 11;
add(stru);        //执行到此会报不支持异常

解决方案 »

  1.   

    how ?
    希望高手们能指点下,我才用c#
    做的是一个智能手持设备上的东东
      

  2.   


    C#中代码:
    ...
      [StructLayout(LayoutKind.Sequential)]   <-- 莫非是这个没加的原因
    public struct stru1
    {
     
      

  3.   

    这个的确是没有加的,不过对简单结构没加好像也可以的
    不知道是不是这个原因,明天我加上试试,先谢谢Dobzhansky
      

  4.   

    的确不是那个问题, 以下测试可行, 估计使用 def 定义导出可以避免名字问题c 代码, cl /LD c.cstruct stru1
    {
      int x;
      int y;
      int xx[2];
    };__declspec(dllexport) int __stdcall
    add(struct stru1 stru)
    {
      return stru.x+stru.y+stru.xx[0]+stru.xx[1];

    c# 调用:using System.Runtime.InteropServices;
    namespace a
    {
      class b
      {
        static void Main()
        {
          System.Console.WriteLine("c");
          stru1 stru;
          stru.xx = new int[2];
          stru.x = 2;
          stru. y = 3;
          stru.xx[0] = 10;
          stru.xx[1] = 11;
          int result = add(stru);        //执行到此会报不支持异常
          System.Console.WriteLine(result);
        }
        [DllImport("c.dll", EntryPoint = "_add@16")] // <- 关键
        public static extern int add(stru1 stru);
      
    //  [StructLayout(LayoutKind.Sequential)]
      public struct stru1
      {
        public int x;
        public int y;
        public int[] xx;
      }
      }
    }
      

  5.   

    _add@16 通过 dumpbin 获知
      

  6.   

    非常感谢Dobzhansky,最近几天应付检查没有来看贴,我按你的方法试了,但还是报异常,报的是找不到DLLl入口点_add@16,因事情比较急我只好把数组抽出成另一个参数,重新做了DLL库。
    不过还是很感谢Dobzhansky的热心帮助!!
      

  7.   


    [StructLayout(LayoutKind.Sequential)]
    public struct stru1
    {
      public int x;
      public int y;
      [MarshalAs(UnmanagedType.ByValArray,SizeConst = 2)]
      public int[] xx1;
    }