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());
感謝reply.In爲了測試error.I修改了C代碼和C#code.but它仍然不工作的權利。 – user1333098 2013-05-03 12:31:20