2013-05-03 74 views
0

我已经从开发C++做了一个DLL,我想调用该函数。 dev的C++这样的代码:从C调用C结构数据#

//the head file 
struct sAdd 
{ 
int* aarr; 
int* barr; 
int length; 
}; 
DLLIMPORT int AddStruct (struct sAdd*); 
//the c file 
DLLIMPORT int AddStruct (struct sAdd* sadd) 
{//sum the aarr and the barr and return the result. 
      int sum=0; 

      int* aarr=sadd->aarr; 
      int* barr=sadd->barr; 
     int numArr=sadd->length;  
      int i; 
      for(i=0;i<numArr;i++) 
      sum+=*(aarr+i); 
      i=0; 
      for(i=0;i<numArr;i++) 
      sum+=*(barr+i); 

      return sum;  
} 

为了调用AddStruct功能,我需要首先定义一个结构。

public struct sAdd 
{ 
    public int[] a; 
    public int[] b; 
    public int length; 
} 
    [DllImport("DllMain.dll", CallingConvention = CallingConvention.Cdecl)] 
    public static extern int AddStruct(ref sAdd sadd); 

的代码来调用AddStruct功能是这样的:

sAdd sadd = new sAdd(); 
    sadd.a = new int[4] { 1, 2, 3 ,4}; 
    sadd.b = new int[4] { 1, 2, 3 ,4}; 
    sadd.length=4; 
    Console.WriteLine("sAdd:" + AddStruct(ref sadd).ToString()); 

结果应该是20,但我得到一个37109984或其他一些大的数字。 所以,我不知道如何改变代码来获得正确的reusult.Maybe我需要使用IntPtr或其他方式??谢谢。

最后,我处理problem.Just修改C#代码。

[StructLayout(LayoutKind.Sequential)] 
    public struct sAdd 
    { 
     public IntPtr a; 
     public IntPtr b; 
    public int length; 
    }; 
      sAdd sadd = new sAdd(); 
      int[] a = new int[4] { 1, 2, 3 ,4}; 
      int[] b = new int[4] { 1, 2, 3 ,4}; 
      sadd.length = 4; 
      sadd.a = Marshal.UnsafeAddrOfPinnedArrayElement(a, 0); 
      sadd.b = Marshal.UnsafeAddrOfPinnedArrayElement(b, 0); 
      Console.WriteLine("sAdd:" + DllMainWrapper.AddStruct(ref sadd).ToString()); 

回答

0

您的C代码已损坏。

当你已经是一个指向第一个元素不能计算使用sizeof数组的长度。只有在范围内有“真实”数组声明时才能这样做。

因此,这:

int* aarr=sadd->aarr; 
int* barr=sadd->barr; 
int numAarr=sizeof(aarr)/sizeof(int); 
int numBarr=sizeof(barr)/sizeof(int);   

坏了,numArr将是一个恒定值(1,如果您的指针大小是相同的整数大小,否则可能2在64位的系统上使用32位int)。

+0

感谢reply.In为了测试error.I修改了C代码和C#code.but它仍然不工作的权利。 – user1333098 2013-05-03 12:31:20