我正在通过Matlab
拨打MCR
来调用P/Invoke
功能。
它抛出一个异常,但我无法解决它,我搜索了很多,但找不到解决方案。
这是错误
[DllImport(@"C:\Program Files\MATLAB\MATLAB Compiler Runtime\v80\runtime\win64\mclmcrrt8_0.dll", EntryPoint = "mclInitializeApplication_proxy", CallingConvention = CallingConvention.Cdecl)]
private static extern bool mclInitializeApplication(string options, Int32 count);
private static void Main(string[] args)
{
var option = "-nojvm";
var result = mclInitializeApplication(option, 1);
Console.WriteLine(result);
Console.ReadLine();
}
答案 0 :(得分:0)
“mclIntializeApplication”的正确编组是:
[DllImport((@"C:\Program Files\MATLAB\MATLAB Compiler Runtime\v80\runtime\win64\mclmcrrt8_0.dll, EntryPoint = "mclInitializeApplication_proxy", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool mclInitializeApplication([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] options, int count);
这是第一个参数是字符串数组(char **)。然后你应该这样称呼它:
var options = new [] { "-nojvm" };
var result = mclInitializeApplication(options, options.Length);
为了避免传递长度并控制布尔结果,您还可以将上面的函数包装到更友好的C#中:
public static void mclInitializeApplication(params string[] options)
{
var count = 0;
if (options != null) { count = options.Length; }
if (!_mclInitializeApplication(options, count))
{
var reason = mclGetLastErrorMessage();
throw new Exception(String.Format("Call to '{0}' failed: {1}", "mclInitializeApplication", reason));
}
}
使用:
[DllImport(@"C:\Program Files\MATLAB\MATLAB Compiler Runtime\v80\runtime\win64\mclmcrrt8_0.dll", EntryPoint = "mclGetLastErrorMessage_proxy", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr _mclGetLastErrorMessage();
public static String mclGetLastErrorMessage()
{
var ptr = _mclGetLastErrorMessage();
return Marshal.PtrToStringAnsi(ptr);
}
但是,在我看来,如果你想要以.NET为目标,最好的解决方案是让Matlab直接使用Mathworks提供的SDK在.NET中编译。