C# 从C调用C结构数据# 我从DEV C++中做了一个DLL,我想调用这个函数。 DeV 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函数的代码如下所示:C# 从C调用C结构数据# 我从DEV C++中做了一个DLL,我想调用这个函数。 DeV 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; },c#,c,dll,call,dev-c++,C#,C,Dll,Call,Dev C++,调用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或其他一些大数字。 因此,我不确
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或其他一些大数字。
因此,我不确定如何更改代码以获得正确的重用结果。也许我需要使用IntPtr或其他方式??谢谢
最后,我处理了这个问题。只需修改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());
你的C代码坏了
如果只有指向第一个元素的指针,则无法使用sizeof
计算数组的长度。只有在作用域中有“真实”数组声明时,才能执行此操作
因此:
int* aarr=sadd->aarr;
int* barr=sadd->barr;
int numAarr=sizeof(aarr)/sizeof(int);
int numBarr=sizeof(barr)/sizeof(int);
如果已损坏,
numArr
将是一个常量值(如果指针大小与整数大小相同,则为1,否则在32位int
的64位系统上可能为2)。谢谢回复。为了测试错误,我已更改了C代码和C代码。但它仍然无法正常工作。
int* aarr=sadd->aarr;
int* barr=sadd->barr;
int numAarr=sizeof(aarr)/sizeof(int);
int numBarr=sizeof(barr)/sizeof(int);