Recently, I need to use a Delphi DLL in my C# project and I have search some answers, however all else fails. The name of DLL was modelDLL.dll, which need another DLL file (I have already put this two files in the debug folder)
Delphi code
type
TCharStr=array[0..599] of char;
Using Delphi to calling DLL works fine (the code is following), however,I don't know the specific comments in DLL File. The relative code of Delphi is as follow:
procedure TMainDLLForm.PedBitBtnClick(Sender: TObject);
var
fileName:TCharStr;
begin
OpenDataFileDlg.InitialDir:= GetCurrentDir;
OpenDataFileDlg.Title:='load model file';
OpenDataFileDlg.Filter := 'model_A[*.mdl]|*.mdl|model_T[*.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('model_T: '+ExtractFileName(FileName));
memo1.Lines.Add(Format('Result: %10s:%0.0f',[targetName,tmpD]));
end;
memo1.Lines.Add('--------------');
memo1.Lines.Add(trim(NIRSAPretreatInfor(FileName)));// calling this function
memo1.Lines.Add('--------------');
memo1.Lines.Add(trim(NIRSAModelInfor(FileName)));
end;
My C# code was following, which hinted "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." error.
[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;
}
}
So, can anyone give me some advices? your reply will be appreciated!
PS: Delphi version: 7.0
import DLL code:
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';
Now I have change the CharSet = CharSet.Auto
to CharSet = CharSet.Ansi
and the error message appeared again.
The call to the PInvoke "NIRSAPre!NIRSAPre.Form1::NIRSAPretreatInfor" function causes the stack to be asymmetric.