Call C structure data from C# -
i have make dll dev c++.and want call function. dev c++ code :
//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 aarr , barr , return 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; } in order call addstruct function,i need define struct first.
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); the code call addstruct function this:
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()); the result should 20,but 37109984 or other big number. ,i not sure how change code right reusult.maybe need use intptr or other ways??thanks .
at last,i deal problem.just modify code in c#.
[structlayout(layoutkind.sequential)] public struct sadd { public intptr a; public intptr b; public int length; }; sadd sadd = new sadd(); int[] = 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());
your c code broken.
you cannot compute length of array using sizeof when have pointer first element. can when have "real" array declaration in scope.
so this:
int* aarr=sadd->aarr; int* barr=sadd->barr; int numaarr=sizeof(aarr)/sizeof(int); int numbarr=sizeof(barr)/sizeof(int); is broken, numarr constant value (1 if pointer size same integer size, otherwise 2 on 64-bit system 32-bit int).
Comments
Post a Comment