我已经从 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 函数,我需要先定义一个结构。
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 或其他一些大数字。所以,我不知道如何更改代码以获得正确的结果。也许我需要使用 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());