After browsing through many discussions on Grasshopper forums, I understand that here I can find the experts that will be able to help me with a problem I have encountered. I have built a dll in C++ which is called from within a GH component, this is the statement I am currently using in the top of my code:
[DllImport(“C:\TopoptForGH\MinC3dmgcg.dll”, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr RunTop3D(int nx, int ny, int nz, double sx, double sy, double sz,
double fr, double vf, double p, int nl, double[] Fin, int nFIXin, int[] FIXin);
Within the main component, the input variables are gathered from several other sub-components where the user can interactively make changes that affect their values. Finally, the component executes the procedure RunTop3D and organizes the output as follows:
protected override void SolveInstance(IGH_DataAccess DA)
{
…
…
…
IntPtr ResultPtr = new IntPtr(0);
ResultPtr = RunTop3D(nelx, nely, nelz, sx, sy, sz, filtrad,
volfrac, penal, nl, RHS, nsup, FIX);
double[] ResultArrayOut = new double[nelx * nely * nelz + 3];
Marshal.Copy(ResultPtr, ResultArrayOut, 0, ResultArrayOut.Length);
ResultPtr = IntPtr.Zero;
…
…
…
DA.SetDataList(0, ResultArrayOut);
}
The problem is: in its first run, the result returned is perfectly correct; in the following runs after the input variables are modified, the results are sometimes meaningless or simply wrong. I tested the same sequence of operations in a standard C# code and it worked fine after modifying input parameters. So I assume I’m doing something wrong with respect to the memory management in Grasshopper and the marshalling of variables. I must admit I am not an expert programmer and quite new to Grasshopper, but in our previous version things worked perfectly – however there were no C++ dll’s there. I understand that many built-in Grasshopper components actually invoke C++ dll’s, so I believe there should be a simple way to do it right – any chance you can give me some idea about what am I doing wrong?
Many thanks,
Oded