Passing a string from C# to Matlab

15 views (last 30 days)
Paul Martin
Paul Martin on 28 Oct 2011
I'm calling a Matlab mcc-compiled DLL from C# and am attempting to marshall a string as an input parameter. I am using .Net PInvoke to load and call the DLL and have declared the method as follows:
public static extern void func([In]Int32 nargout, ref IntPtr h, [In][MarshalAs(UnmanagedType.LPStr)]string path);
and the call as:
string dataPath = "c:\\path\\data";
int nargout = 1;
IntPtr h = IntPtr.Zero;
func(nargout, ref h, dataPath);
This results in an exception "Attempt to read or write protected memory".
I have also tried passing a char array:
char[] tmpStr = dataPath.ToCharArray();
func(nargout, ref h, tmpStr);
And have tried using the runtime mxCreateString function: [DllImport("mclmcrrt72.dll", EntryPoint = "mxCreateString", CharSet = CharSet.Ansi)] static extern IntPtr CreateString([In][MarshalAs(UnmanagedType.LPArray)] char[] myString);
with call:
IntPtr strPtr = CreateString(myStr);
func(nargout, ref h, tmpStr);
However, the same exception is encountered.
Without the string parameter, the call succeeds.
Has anyone succeeded in doing this?
Thanks in advance.

Answers (0)

Categories

Find more on MATLAB Compiler SDK in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!