Hi
I need to make repeated calls to a matlab DLL from C#. I have searched the websites and tried the various methods but somehow I couldn't get them to do what I need them to do. Initially I got memory access violation error, then invalid handle error using the GCHandle approach and finally for the codes below, I got garbage value returned from the DLL.
Could anyone please point me to the right way? Thanks.
Simplified codes:
============
class DllWrapper
{
...
[DllImport(@"libtest.dll")]
private static extern void mlfTest(int num, ref IntPtr theOutput, [In]IntPtr theInput);
...
public static double CallDLL(string input, IntPtr outVal)
{
...
double[] ans = new double[1];
//initialize libraries
...
//initialize arguments
IntPtr inVal = mxCreateString(input);
//call library function
mlfTest(1, ref outVal, inVal);
//get return value
Marshal.Copy(mxGetPr(outVal), ans, 0, 1);
//terminate libraries
...
return ans[0];
}
}
.......
static void Main(string[] args)
{
...
for (int i = 0; i < 3; i++)
{
IntPtr outPtr = Marshal.AllocHGlobal(100);
double retDouble = DllWrapper.CallDLL(path, outPtr);
Console.WriteLine("The return value is : " + retDouble);
if (outPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(outPtr);
outPtr = IntPtr.Zero;
}
}
}