智慧土狼
2018-10-24 01:47
采纳率: 50%
浏览 879

C#调用Delphi dll文件问题

最近手头一个项目,需要用到C#调用Delphi写出的dll文件(调用的是modelDLL.dll,但是该dll文件还需要另外一个borlndmm.dll文件支持,调用的时候已经把这两个dll文件放到debug目录下了),直接附上相关代码:

Delphi相关源码:

type
    TCharStr=array[0..599] of char;

用Delphi写的直接调用可运行,代码如下:

procedure TMainDLLForm.PedBitBtnClick(Sender: TObject);
var
  fileName:TCharStr;
begin

        OpenDataFileDlg.InitialDir:= GetCurrentDir;
        OpenDataFileDlg.Title:='加载模型文件';
        OpenDataFileDlg.Filter := '定量模型[*.mdl]|*.mdl|定性模型[*.mdr]|*.mdr';
        if OpenDataFileDlg.Execute then
        begin
           StrPCopy(FileName,OpenDataFileDlg.FileName);
           tmpD:=NIRSAModelForPred(graphyData,dataLength,FileName,targetName);
        end;  
       if compareText(fileExt,'.MDR')=0 then
       begin
         memo1.Lines.Add('定性模型: '+ExtractFileName(FileName));
         memo1.Lines.Add(Format('预测结果: %10s:%0.0f',[targetName,tmpD]));
       end;
            memo1.Lines.Add('--------------');
            memo1.Lines.Add(trim(NIRSAPretreatInfor(FileName)));//调用该函数
            memo1.Lines.Add('--------------');
            memo1.Lines.Add(trim(NIRSAModelInfor(FileName)));
end;

而我现在用C#调用出现"尝试读取或写入受保护的内存。这通常指示其他内存已损坏"的错误,代码如下所示:

 [MarshalAs(UnmanagedType.LPStr, SizeConst = 600)]
        public string fileName;

        [DllImport(@"modelDLL.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.LPStr, SizeConst = 600)]
        public static extern string NIRSAPretreatInfor(ref string fileName);

        private void preCalcButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileName = dialog.FileName;
                string result = NIRSAPretreatInfor(ref fileName);
                modelInfoTextBox.Text = result;
            }                       
        }

该段代码主要参考Stack Overflow的一些解决方案,地址:链接,现在解决不了,没有C币了,请大神支支招,谢谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • threenewbee 2018-10-24 04:43

    [MarshalAs(UnmanagedType.LPStr, SizeConst = 600)]
    public string fileName;

    这个换成
    public StringBuilder fileName = new StringBuilder(600);

    打赏 评论
  • 智慧土狼 2018-10-24 11:18

    PS: Delphi 版本: 7.0

    Delphi导入DLL代码:

     implementation
           function  
    NIRSAModelForPred(Data:TGraphyData;dataLength:integer;ModelFileName:TCharStr;var targetName:TCharStr):double;stdcall;external 'modelDLL.dll';
           function  NIRSAModelInfor(ModelFileName:TCharStr):TCharStr;stdCall;external 'modelDLL.dll';
           function  NIRSAPretreatInfor(ModelFileName:TCharStr):TCharStr;stdCall;external 'modelDLL.dll';
    
    打赏 评论

相关推荐 更多相似问题