c#调用dll函数返回值异常

.Net技术 码拜 7年前 (2017-05-08) 2080次浏览
本人用c#调用的c++写的dll,其中c#代码如下

     namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport(@"smallT_BJ.dll", EntryPoint = "test", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern IntPtr test([MarshalAs(UnmanagedType.LPStr)]ref string path);
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            string path = " C:\2.bmp";
            IntPtr init = Marshal.StringToHGlobalAnsi(path);
            IntPtr path1 = Marshal.AllocHGlobal(100);  
            path1 = test(ref path);
            MessageBox.Show(path1.ToString());
        }
    }
}

其中.h文件如下

#include <memory>
#include <stdlib.h>
#include <math.h>
#include <time.h>
using namespace std;
using namespace cv;
#ifdef SMALLT_BJ_EXPORTS
#define SMALLT_BJ_API __declspec(dllexport)
#else
#define SMALLT_BJ_API __declspec(dllimport)
#endif
SMALLT_BJ_API Mat filters(Mat source, int thresholdin);
SMALLT_BJ_API Mat filterspatial2(Mat source, int th);
SMALLT_BJ_API void cmedian(Mat src, Mat dst, int innerbox_size, int outerbox_size);
SMALLT_BJ_API Mat prefilter(Mat source);
SMALLT_BJ_API vector<Mat> getSuspects(Mat& frame, Mat src, int box_size, vector<Point>& LeftUpPoints, vector<vector<Point>>& cont);
extern "C" SMALLT_BJ_API Point smallTarget(const char* file);
extern "C" SMALLT_BJ_API const char* test(const char* file);

其中test函数就是一个作用,输入什么输出什么,例如本人想test函数输入的为“123abc”,他的返回值就是”123abc”。而且在c++函数中调用dll正确,可是用C#调用出现了问题,就是输入的是字符串,输出的却是数字,并且每次输入的字符串相同输出的字符串却不同。并且还没用任何异常。求指导。怎么回事

解决方案

50

你用 C++  来呼叫也不正确。
而且这种导出符号就是错误的。
返回的 char const * 由谁来释放。
除非他是一个静态的数组空间。
返回 String 就可以了。 MarshalAs.LPSTR
假如要返回字符串,使用 BSTR 来返回。
否则传入字符串空间。
例如 BOOL  Test(char const *strIn, char *strOut, size_t size);

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c#调用dll函数返回值异常
喜欢 (0)
[1034331897@qq.com]
分享 (0)