wiki:dokuwiki:cs:delphi製dllをc

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】

  1. library sample;
  2. uses
  3. System.SysUtils,
  4. System.Hash,
  5. System.Classes;
  6.  
  7. {$R *.res}
  8. function tosha2(val : WideString ): WideString; stdcall;
  9. begin
  10.  
  11. Pointer(Result) := nil;
  12. //Result := val;
  13. with THashSHA2.Create(SHA384) do
  14. begin
  15. Update(val);
  16. Result := HashasString;
  17. end;
  18.  
  19.  
  20. end;
  21. exports
  22. tosha2;
  23. begin
  24. end.
  • 文字列型の引数と戻り値はWideString型で定義します。
  • Resultは、一度nilを代入しておきます。

 »さらっと参考URLを読んでください。

【C#】

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11.  
  12. namespace learning
  13. {
  14. public partial class Form1 : Form
  15. {
  16.  
  17. [DllImport("sample.dll")]
  18. public static extern void tosha2([MarshalAs(UnmanagedType.BStr)] out string Result, [MarshalAs(UnmanagedType.BStr)] string val);
  19.  
  20. public Form1()
  21. {
  22. InitializeComponent();
  23. }
  24.  
  25. private void button1_Click(object sender, EventArgs e)
  26. {
  27. string str;
  28. tosha2(out str, textBox1.Text);
  29.  
  30. textBox2.Text = str;
  31. }
  32. }
  33. }

注目すべき点は、DELPHI側の戻り値のSTRING型は、C#では、OUTパラメータになるということです。参考URLを読めば分かりますが、どうやら、パラーメタがいくつあっても1番目のパラメータがoutパラメータになり戻り値を取得できるようです。

delphiのinteger型などの標準の型の場合は、voidでなく、関数の戻り値として取得できます。

【実行結果】

コメントを入力. Wiki文法が有効です:
 
  • wiki/dokuwiki/cs/delphi製dllをc.txt
  • 最終更新: 2024/11/04 00:47
  • by 127.0.0.1