Delphi製DLLをC#から呼び出す
How to call Delphi DLL from C# Function with String on args
ここでは、String型を使うためのツッコミどころを紹介します。
参考URL
https://stackoverflow.com/questions/9349530/why-can-a-widestring-not-be-used-as-a-function-return-value-for-interop
https://stackoverflow.com/questions/16601423/calling-a-delphi-method-in-a-dll-from-c-sharp
【DELPHI】
- library sample;
- uses
- System.SysUtils,
- System.Hash,
- System.Classes;
- {$R *.res}
- function tosha2(val : WideString ): WideString; stdcall;
- begin
- Pointer(Result) := nil;
- //Result := val;
- with THashSHA2.Create(SHA384) do
- begin
- Update(val);
- Result := HashasString;
- end;
- end;
- exports
- tosha2;
- begin
- end.
- 文字列型の引数と戻り値はWideString型で定義します。
- Resultは、一度nilを代入しておきます。
»さらっと参考URLを読んでください。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace learning
- {
- public partial class Form1 : Form
- {
- [DllImport("sample.dll")]
- public static extern void tosha2([MarshalAs(UnmanagedType.BStr)] out string Result, [MarshalAs(UnmanagedType.BStr)] string val);
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- string str;
- tosha2(out str, textBox1.Text);
- textBox2.Text = str;
- }
- }
- }
注目すべき点は、DELPHI側の戻り値のSTRING型は、C#では、OUTパラメータになるということです。参考URLを読めば分かりますが、どうやら、パラーメタがいくつあっても1番目のパラメータがoutパラメータになり戻り値を取得できるようです。
delphiのinteger型などの標準の型の場合は、voidでなく、関数の戻り値として取得できます。
コメント