I want to use c++ code in my C# scripts for rendering some objects in unity 3d.
I have compiled the C++ script as a dll (lammps.dll) and have written a wrapper C# script to invoke a few functions from C++ script.
I am able to access void* and int* pointer successfully by doing the following:
Example:
C++ prototype:
void *lammps_extract_global(void *ptr, char *name);
Equivalent C# prototype (in CSharpLibrary.cs file):
DllImport("lammps.dll", EntryPoint = "lammps_extract_gloabl", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall);
public static extern IntPtr lammps_extract_global(IntPtr ptr, [MarshalAs(UnmamanegType.LPStr)]String name);
Then I compile the C# file as a file which produces CSharpLibrary.dll
In another C# script I am using CSharpLibrary wrapper to access C++ functions as:
1. First define lmp_ptr as,
var lmp_ptr = Marshal.AllocHGlobal(Marshal.Sizeof(typeof(System.IntPtr)));
2. Get lmp_ptr from C++ and dereference it as,
var deref1 = (System.IntPtr)Marshal.PtrToStructure(lmp_ptr, typeof(System.IntPtr))
3. Then use deref1 to get natmPtr as,
System.IntPtr natmPtr = CSharpLibrary.CSharpLibrary.lammps_extract_global(deref1, "natoms");
4. Convert natmPtr to an integer as,
int nAtom = (int)Marshal.PtrToStructure(natmPtr, typeof(int))
Step 4 gives me appropriate value of nAtom.
I want to do the same thing as done for nAtom to another float pointer to pointer matrix storing positions.
I did this to get the float pointer to pointer reference in C#
Considering lammps_extract_atom has been defined similar to the function explain above, we have
System.IntPtr posPtr = CSharpLibrary.CSharpLibrary.lammps_extract_atom(deref1, "x")
Here posPtr is a float** value being returned from C++
Similar statement in C++ would have looked like
float** posPtr = (double**)(lammps_extract_atom)(void *lmp_ptr, char *name)