通过P / Invoke从C#调用Matlab DLL函数不会给出预期的输出

时间:2016-03-11 17:33:40

标签: c# matlab pinvoke unmanaged native-code

我写了一个简单的matlab函数,它连接了两个字符串:

mcc -B csharedlib:libtestCat testCat

我使用以下命令从中创建了一个DLL:extern LIB_libtestCat_C_API bool MW_CALL_CONV mlfTestCat(int nargout, mxArray** z, mxArray* x, mxArray* y);

这是函数的签名在libtestCat.h中的样子:

        [DllImport(@"libtestCatNew.dll")]
                private static extern void libtestCatNewInitialize();
        [DllImport(@"libtestCatNew.dll")]
                private static extern void libtestCatNewTerminate();
        [DllImport(@"libtestCatNew.dll", CharSet = CharSet.Ansi, EntryPoint = "mlfTestCat", CallingConvention = CallingConvention.Cdecl)]
        private static extern bool testCat([In]Int32 num, ref IntPtr output, [In]IntPtr input1, [In]IntPtr input2);

        [DllImport(@"libmx.dll")]
        private static extern IntPtr mxCreateDoubleScalar([In]double value);

        [DllImport(@"libmx.dll")]
        private static extern IntPtr mxCreateString([In]Char[] str);

        [DllImport(@"libmx.dll")]
        public static extern int mxGetString(IntPtr array_ptr, StringBuilder buf, int buflen);

                string context = "hi";
                string query = "how are you";

                bool ret = mclInitializeApplication_proxy("NULL", 0);
                  libtestCatNewInitialize();

                IntPtr contextIP1 = mxCreateString(contextCA);
                ViewBag.FinalText += " ContextIP1:";
                StringBuilder contextSB1 = new StringBuilder(200);
                mxGetString(contextIP1, contextSB1, 200);
                ViewBag.FinalText += contextSB1;
                IntPtr queryIP1 = mxCreateString(queryCA);
                ViewBag.FinalText += " QueryIP1:";
                StringBuilder querySB1 = new StringBuilder(200);
                mxGetString(queryIP1, querySB1, 200);
                ViewBag.FinalText += querySB1;
                IntPtr responseIP1 = mxCreateString(responseCA);
                bool ret2 = testCat(1, ref responseIP1, contextIP1, queryIP1);
                ViewBag.FinalText += " responseIP1:";
                StringBuilder responseSB1 = new StringBuilder(200);
                mxGetString(responseIP1, responseSB1, 200);
                ViewBag.FinalText += responseSB1;

接下来,我创建了一个C#Azure项目(MVC + Web API),并包含上面创建的DLL。我导入并调用它如下:

ViewBag.FinalText = ContextIP1:hi QueryIP1:how are you responseIP1:dummy response

然而,responseSB1仍然保持不变。以下是最终字符串的样子:

Int

从Matlab执行时,该功能绝对正常。我想我在调用函数时遇到了一些错误。有人可以帮我理解我哪里出错吗?

0 个答案:

没有答案